Arduino vs Wemos Fan control I have a working fan control with the correct wiring that works with arduino.

I would like to change the arduino with a Wemos D1 mini board.

When I hook everything up. The fans are not activated.

The fan is driven by a 12v charger. And the irf540n cicruit powers that. They just share a common ground and the pwm pin D5

Is there something I need to know about the difference in both of them?

Below is the code, I've changed D5 in the code to 14.

Still nothing seems to work.

    #define fan D5

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("start");
  pinMode(fan, OUTPUT);

  digitalWrite(fan, LOW);
}

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

  delay(1000);
  digitalWrite(fan, LOW);
}

The IRF540 is not suitable to be controlled by a 3.3V device because it has a gate-source-threshold voltage of 2-4V (that's the voltage at which the mosfet starts to conduct, but you need to be above that voltage). While this worked at 5V logic level on the arduino, the 3.3V are not enough to make the mosfet switch entirely.

A suitable mosfet has a threshold voltage below 1V. Also for a fan, you eon't need a big mosfet rated for 30A, a tiny one will do it.


Can you use an Arduino UNO as an EEPROM programmer Hi I have an Arduino UNO and a AT28c64B and a single shift register, is it possible to make an EEPROM programmer with it? I’m not too good with the Arduino to do a lot of trial and error... I would just like to know if it’s possible or not, not how to...

You need 24 GPIO pins to control that EEPROM chip. The Arduino has 19, and a typical shift register has 8 outputs. It takes 3 or 4 (depending on the shift register) to drive the shift register.

That's 19 + 8 - 4 = 23 for a shift register that needs 4 pins, or 19 + 8 - 3 = 24 for one that needs 3 pins.

However I would assume that you want to communicate with your computer as well, and that means that pins 0 and 1 of the Arduino are out of bounds, since they are used for the PC communication.

That means, at best, you have 22 pins when you need 24.

So, no, with that combination you can't, due to a lack of pins.

However an IO expander, such as the MCP23017, would give you enough pins and need fewer pins to drive. They also work in both directions, so can be used for pins that want to be read as well as written (data pins).

Alternatively an SPI or I2C connected EEPROM would be the better option, since those are designed to be driven by a small microcontroller like an Arduino uses.


Running both sensor and addressable LED strips at a same time? I'm trying to obtain the sensors' readings as well as making the LED strips to light up at this particular pattern, if the sensor readings reaches certain values. But since both of these codes are inside the void loop(), there will be a problem. How can I do this correctly?

void loop()
{
    currentSensorReading = analogRead(sensorPin);
    Serial.println(currentSensorReading );

    if(currentSensorReading is in range of certain values){
        rainbowCycle(20);
    } else { turn LEDs off }
}

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

Rewrite without using delay(). Or alternatively, do the test inside the for loop as well, eg.

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);

    // ----------- ADD THESE THREE LINES ---------------
    currentSensorReading = analogRead(sensorPin);
    if(currentSensorReading is NOT in range of certain values)
        return;

  }
}


Sim800l gsm module cannot connect gprs data I am a rookie to arduino. I am trying to access MQTT server using Sim800l coreboard GSM module with Adafruit Fona/Tinygsm library but failed.So I decided to check http GET/POST request with AT command first.In AT commands all the basic commands following www.exploreembedded.com/wiki/Setting_up_GPRS_with_SIM800L  works fine  but whenever I make a GET request by "AT+CIPSTART=" module restart itself.I also tried seeduino library GPRS_HTTP example, it gives me "error:CIPSTART" and restarts module.Though this code worked one time only,this is the code

#include <gprs.h>
#include <SoftwareSerial.h>

char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt
HTTP/1.0\r\n\r\n";
char buffer[512];

GPRS gprs;

void setup() {
Serial.begin(9600);
while(!Serial);
Serial.println("GPRS - HTTP Connection Test...");
gprs.preInit();
while(0 != gprs.init()) {
 delay(1000);
 Serial.println("init error");
}
while(!gprs.join("gpinternet")) {  //change "cmnet" to your own APN
  Serial.println("gprs join network error");
  delay(2000);
}
// successful DHCP
Serial.print("IP Address is ");
Serial.println(gprs.getIPAddress());

Serial.println("Init success, start to connect mbed.org...");

if(0 == gprs.connectTCP("mbed.org", 80)) {
  Serial.println("connect mbed.org success");
}else{
  Serial.println("connect error");
  while(1);
}

Serial.println("waiting to fetch...");
if(0 == gprs.sendTCPData(http_cmd))
{
gprs.serialDebug();
}

//  gprs.closeTCP();
//  gprs.shutTCP();
//  Serial.println("close");
}

void loop() {

}

also tried this commands and module got restarted after AT+HTTPACTION=0 this last command

module power and sim configure are fine as far I know,please help me find out what am I doing wrong?Sorry for making this long.please ask me if I couldn't make the question clear.TIA

I get it now , a stable power source is the answer. arduino with usb can give right amount of Volts but it lacks stable power(amps i guess) while making a TCP connection, that's why module keep restarting.Although it works fine with call, text etc. powering arduino with an AC adapter solves my problem ,now it can connect to mqtt too.Thanks


Sea level pressure for BMP280 I have a BMP280 and BMP180 pressure sensor and I have both of them connected via I²C to a ESP8266.
For the BMP180, I can get the sea level air pressure when I pass the pressure and altitude like so:
// https://github.com/sparkfun/BMP180_Breakout_Arduino_Library
#include <SFE_BMP180.h>
SFE_BMP180 bmp180;
[...]
Serial.print(bmp180.sealevel(pressure, 800));

Is there a similar thing for the BMP280? Reading pressure and temperature works fine:
#include <Adafruit_BMP280.h>
Adafruit_BMP280 bmp280;
[...]
double temperature = bmp280.readTemperature();
double pressure = bmp280.readPressure() / 100;

It seems this was planned for the Adafruit BMP280 library but not implemented. Looking at Adafruit_BMP280.h we see commented code that has a method seaLevelForAltitude():
/*
class Adafruit_BMP280_Unified : public Adafruit_Sensor
{
  public:
    Adafruit_BMP280_Unified(int32_t sensorID = -1);

    bool  begin(uint8_t addr = BMP280_ADDRESS, uint8_t chipid = BMP280_CHIPID);
    void  getTemperature(float *temp);
    void  getPressure(float *pressure);
    float pressureToAltitude(float seaLevel, float atmospheric, float temp);
    float seaLevelForAltitude(float altitude, float atmospheric, float temp);
    void  getEvent(sensors_event_t*);
    void  getSensor(sensor_t*);

  private:
    uint8_t   _i2c_addr;
    int32_t   _sensorID;
};

*/

In another library, BMP280-arduino-library, I found a function that seems to work:
double BMP280::sealevel(double P, double A)
// Given a pressure P (mb) taken at a specific altitude (meters),
// return the equivalent pressure (mb) at sea level.
// This produces pressure readings that can be used for weather measurements.
{
    return(P/pow(1-(A/44330.0),5.255));
}

First, I just copied that function into my code (without the class name), due to the friendly pizza license. Later I switched to that library and it also worked fine.


Button reading not going off I made a circuit which in my intentions would allow me to toggle a LED dimming loop.

Problem is that once I push the button the first time pushing it a second time doesn't toggle the LED loop off.

Here is the code:

const int LED = 9; // the pin for the LED
const int BUTTON = 7;

int val = LOW;

int old_val = LOW;
int state = 0;
int i = 0;

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT);

}

void loop()
{
  val = digitalRead(BUTTON);

  if ((val == HIGH) && (old_val==LOW))
  {
    state = 1 - state;
    delay(10);
  }

  old_val = val;

  if (state == 1)
  {
    for (i = 0; i < 255; i++)  // loop from 0 to 254 (fade in)
    {
      analogWrite(LED, i); // set the LED brightness
      delay(10);           // Wait 10ms because analogWrite
      // is instantaneous and we would
      // not see any change
    }

    for (i = 255; i > 0; i--) // loop from 255 to 1 (fade out)
    {
      analogWrite(LED, i); // set the LED brightness
      delay(10);           // Wait 10ms
    }
  } else
  {
    analogWrite(LED, 0);
  }

  if ((val == LOW) && (old_val == HIGH))
  {
    delay(10);
  }
}

Here is the circuit scheme:

I would be interested both in learning what the problem is AND learning any mental methods I can apply to debug in such situations.

While the led is fading in and out (which takes 5 seconds), the state of the button is never checked. So you'd need to have the button released for at least 5 seconds (so old_val becomes LOW), and then pressed exactly we the led is faded out (again, 5 seconds later). So try keeping the button pressed for at least 5 seconds.

You probably want to rewrite your code, so the button is more 'responsive'. Below I added an example of how to do this.

const int LED = 9; // the pin for the LED
const int BUTTON = 7;

int val = LOW;
int old_val = LOW;

bool fadeLed = false;
int brightness = 0;//current pwm value
int direction = 1;// 1 is brightness is increasing, -1 if brightness is decreasing

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

void loop()
{

  /* check the button */
  val = digitalRead(BUTTON);
  if ((val == HIGH) && (old_val==LOW))
  {
    // button pressed ( called only once per press )
    fadeLed = !fadeLed;// invert boolean
  }
  old_val = val;

  /* update the leds brightness */
  if( fadeLed )
  {
    // fade led in and out
    if( brightness==0 )
      direction = 1;//change direction is minimum value reached
    if( brightness==255 )
      direction = -1;//change direction is maximum value reached
    brightness += direction;// increase/decrease brightness
  }
  else
  {
    // fadeLed is disabled, so only decrease brightness till it reaches zero
    if( brightness>0 )
      brightness--;
  }

  analogWrite(LED, brightness); // set the LED brightness
  delay(10);           // Wait 10ms because analogWrite
                       // is instantaneous and we would
                       // not see any change

}

Any questions about the code; just let me know.


Reading Analog values of bluetooth module HC 05 I am working on a project which requires signal strength of a bluetooth TX and RX. what i assume is that in bluetooth module like hc05, there is an antenna receiver which reads the analog signal and then passes it to its ADC to get data in terms of 0's and 1's. But is there any way i can read the analog signal strength of the reveiver antenna directly? Please help

Try looking up the datasheet to see if there is a command for signal strength. It's impossible to directly read the the analog value since the signal strength is way too low in amplitude.


Alternative Rx/Tx Pins for Arduino Uno and Pro Mini Do they have specific pins that is best to be use as Rx/Tx pins (aside from D0 and D1)? If so, what makes them special?

edit: What pin feature i should look out for when choosing the rx/tx pin? Is there any specific pins that will make it a better rx/tx pin?

Pins D0 and D1 are used for hardware serial, see Serial library reference.

You can use any other pins for virtual Rx/Tx lines employing a software serial mode, for example by using the SoftwareSerial library, see Software Serial example, or by implementing your own custom code, or custom library.


Import into Arduino a vintage data bus from TMS1000 For experimentation I want to import or receive into Arduino the output data from a TMS1000 (1980s) data bus.  For model train controller Hornby Zero1, and the bus sends data to receivers, for loco number, speed, direction etc. I have all the data structure etc) Is it feasible  to import to Arduino, and export from the same Arduino back to the original bus.    Just to see it working, and then later experiment with the data in the Arduino.
What libraries would be best ?
Thanks
Charles Harris

You're not going to find any pre-built libraries for this task which is somewhat unusual but not at all impossible.
Basically all you need to do is to connect the TMS1000 address/data and strobe lines to Arduino inputs and write yourself some relatively simple code to detect the various TMS1000 bus states and capture them when they happen.  In order to detect specific events as you have mentioned you will need to know more about the TMS1000 software that's running and what I/O devices that it's selecting.  But again, that's all pretty straightforward.
Keep in mind, however, that you are going to have to perform level shifting on ALL the inputs from the TMS1000.  This old TI chip was implemented using a PMOS (i.e. a predecessor to both NMOS and CMOS) and uses a NEGATIVE power supply instead of the more common today POSITIVE supply.
So rather than being powered by a +5V supply the way an Arduino is, the TMS1000 is powered by a -15V supply.  In this case ground is still at 0V but Vdd is -15V.  That means the I/O signals adhere to a different scheme as noted in the datasheet:

You can view the datasheet yourself at:
TMS1000 Datasheet
But what this means is that a LOW (i.e. Vil) is at -15V and a HIGH (i.e. Vih) is at 0V.  You will need to translate these voltages so that you don't damage either the TMS1000 or the Arduino and you get the correct levels on the pins that you are watching.
The TMS1000 datasheet has some suggested circuits for interfacing to 74LSxx series parts (i.e. 5V logic) which will probably get you started.  Note that the simplest method involves running the 5V logic with its VDD at 0V and it's "ground" at -5V.  While this might seem odd, the Arduino will not know the difference as voltage is always relative.


ArduCam ESP8266 and (Not-Mini) OV2640 Camera Module interface? I bought ArduCam ESP8266 and a OV2640 Module. However it is not the mini-version. At the time it didn't seem like it was necessary.

I might have made a big mistake here.

The board has 8 female pins specifically for the camera module. But the OV2640 module has 20 male pins. A mini-version of the same camera leaves 8 pins, and has a nice interface.

I might have to send this back and get that one, but I want to know if it's possible to simply use this one and wire it up with certain pins instead?

Links to the two products to be specific:
http://www.arducam.com/camera-modules/2mp-ov2640/ (Camera)
http://www.arducam.com/arducam-esp8266-uno-board-arduino-camera/ (Board)

Thanks for your help,

Fred

No, you can't "mix and match" like that. The 8-pin header has I2C and SPI on it for a "cooked" video interface. The 20-pin interface has the "raw" camera CSI interface.

The difference is, the mini version has its own small video processor and FIFO chip on it which processes and buffers the video image allowing you to take a picture then slowly stream that data back through to the slow Arduino at a speed it is comfortable with. The non-mini version doesn't have that and relies on the host controller board having enough power to process a live CSI video signal, which the Arduino cannot do.


Why doesn't Serial.read() read multiple character? I used multiple of Serial.read() and Serial.parseInt() to get characters and a number ( like "xy123" ) on an Arduino UNO.
Then I checked the result on Serial monitor.

Unfortunately I couldn't get the character with second Serial.read().

Here's the code:

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

void loop(){
  if (Serial.available() >0) {

    // I want to reacive the characters like "xy123"
    char input1 = Serial.read();
    char input2 = Serial.read();
    int value = Serial.parseInt();

    Serial.println(input1); // ok
    Serial.println(input2); // * no good * (-1)
    Serial.println(value);  // ok

    // Writing some codes with input1 ,input2 and value ...
  }
// I don't want to use delay().
}

How do I get the second character?

Thanks.

if (Serial.available() >0) {

This is like saying "I won't go into that room until there is at least one dog in there".  Someone tells you there is a dog there. You go into the room and say "Hey, why aren't there two dogs there?".

If you want to read two bytes one approach is to wait until they are available:

  if (Serial.available() >= 2) {


Why does my servo execute an action in the beginning when the odds are almost 0? I made a servo motor turn if the result of random(0, 10000) is less than or equal to 1. If that is the case, the motor turns to 130 degrees, to 50 degrees, and then to default position(90 degrees). It works well except whenever I turn on the Arduino, it automatically executes the turning maneuver. It usually takes dozens of seconds for the randomNum to be 1 or 0. However, the servo always turns right away at the beginning. Here is my code. I will make comments to help you understand what I was thinking. I used no delays.

#include <Servo.h>
Servo servo;
unsigned long timer=millis();//counter
unsigned long servoTimer;
boolean turned130 = false;
int randomNum;//will hold value 0-9999
bool backCheck = false;//variables to keep track which code block to call
bool checkingAllowed = false;
bool turned50 = false;
bool startChecking = false;

void setup() {
servo.attach(12);
servo.write(90);//set default position
servoTimer=millis();
}

void loop() {
timer=millis();//update counter each time
if(checkingAllowed==false){
randomNum = random(0, 10000);//random number generator
if(randomNum<=1){//small odds
  checkingAllowed = true;//makes this codeblock unable to run
  servoTimer=millis();
  servo.write(130);
  turned130=true;/sets variables to allow other if statements to run
  turned50=false;
}
}
if(timer-servoTimer>=1000 && turned130==true && checkingAllowed==true && turned50==false){//next codeblock that runs if random <= 1 after 1 second
turn50();
}
if(timer-servoTimer>=1000 && turned130==false && checkingAllowed==true && turned50==true){
turnBack(); one second later this runs
}
if(timer-servoTimer>=1000 && checkingAllowed==true && backCheck==true){
  backCheck=false;//servo turns back to 90
  checkingAllowed = false;//allows the main code block to be called
}

delay(2);//small delay
}

void turnBack(){
random50 = random(0, 160);
servoTimer=millis();
servo.write(90);
backCheck = true;
turned50=false;
}
void turn50(){
turned130 = false;
random130  = random(0, 160);
servoTimer = millis();
servo.write(50);
turned50=true;
}

It takes a while for the random number to be 1 or 0. I do not understand how 100% of the time, the servo executes the maneuver in the beginning. I will give any more information if you need it to aid me. The random() will soon be replaced by ping() of ultrasonic sensor. Then, the problem will probably disappear. I just want to be clear on what is happening here.

Recognise that, despite the name, random() does not produce a truly random number. Because a computer is basically determinate, every time random() is called it produces results in a fixed sequence - it is possible that this sequence includes 0 or 1 straight away.

If you want it to start at a different point, you need to "seed" the random number generator by calling randomSeed() and passing in an integer. Note that it can't be the same integer every time - that would just move the sequence to the same point every time. The Arduino reference for random() suggests reading an unconnected analog input with analogRead() (which would produce different numbers at different instances in time) to "seed" the random number generator with a new starting position.

randomSeed(analogRead(A0)); // Seed random() with random starting point


Best way to make an Arduino switch 8 12V LED's I'm trying to switch multiple 12V LED's with my arduino, based on the input of a (serial-in parallel-out) shift-register.

The 12V comes from a separate battery, so I can use 8 mosfets to get my 12V, and I might even put a parallel-in serial-out shift register in between.

But I'm hoping that there is a cleaner way of doing this.
Is there some kind of component that combines a shift register and a mosfet?

Any ideas on the best way to solve this?

I would recommend using something like the STP08DP05.  ST Microelectronics makes 16 and 24 bit versions as well.  You can also find TI and NXP parts that will do basically the same thing.

With these parts you can hardwire your max current value with a resistor to make sure you don't overdrive the LED.  Just because you can drive the LED at 90mA, doesn't mean you should... it will probably be way to bright.  The IC's can also be daisy-chained to your shift register and you can drive very large strings of LEDs... or use them for RGB LEDs.

Hope that helps!

EDIT - Based on Comments

There are a couple of options.  Note the Vdd represents the voltage supply to the IC itself and the nominal operating voltage is 3.0V up to 5.5V (I'm honestly not sure why they even added 7V as a max value when they specify 5.5V on the next page).

So, Vdd is not necessarily the voltage that your LED's are driven at.  You can drive the LEDs at 12V  (if you need to) and add a series resistor to the OUT pins of the IC's to dissipate the extra heat.

You would probably be fine with 200 ohms per pin.  If you set your current at 20mA, and assuming a 2.2V drop through the LED, that would give you approximately 5.8V at the OUT pins and the IC wouldn't have to dissipate much heat in terms of power.

However, if you don't need to drive them at 12V then I wouldn't bother.  Usually the forward voltage of an LED is 1.8 to 3.3V and you don't need 12V.  However, if you are driving a lot of them then it may be easier to use the 12V.  There are always trade-offs.


Reading iBeacon Data using HC-05 bluetooth module I have bought a HC-05 bluetooth module for Arduino.

My requirement is to read data transmitted from iBeacon, is it possible using HC-05 or I have to shift to HM-10?

The HC-05 doesn't support BLE, which is used for iBeacons.


upload real time ultrasonic sensor data to pubnub using arduino and esp8266 I want to upload the real time data of ultrasonic sensor attached to my Arduino  Uno and I have been using esp8266 module for the WiFi connection.

I want to upload to PubNub but I don't know how to start writing the code for PubNub and where do I have to write the code.

I have the code working on my Arduino using the ultrasonic sensor in C++ language, printing the readings on the serial monitor. However, the code will be definitely changed in order to upload the sensor readings to PubNub.

On PubNub the most used SDK is JavaScript and I'm not very familiar to it. For C++ the most used SDK is Posix but it seems way more difficult more than JavaScript. So how I have to translate the code from C++ to JavaScript to get it published on PubNub?

Sorry, I am completely new to this stuff therefore I don't know much about it.

The PubNub website has a link to an Arduino library:

https://github.com/pubnub/arduino

Although it doesn't have specific support for the ESP8266 per se, it does support the Arduino Ethernet Shield, Arduino Wifi Shield and Arduino Wifi101 Shield, so I would imagine it wouldn't be hard to adapt the code.

Be aware that for the Arduino Uno, the SRAM will be fairly limited, where as the  ESP8266 contains 96 KB of DRAM.


Can I use a ThunderBorg is a dual motor controller on an Arduino UNO R3 I am new to Arduino and Electronics and am thinking of making a 6 wheel drive all terrain platform similar to the MonsterBorg pi, but I want to use an Arduino instead of a Raspberry pi  to control the motors. The motors I intend to use need to be powerfull.
Any advice on what would be shield or motor controllers I should use would be a great help.

Hello,
You have many possibility for drive one or more motor.

Transistor(1 motor)
L293D(2 motor backward and forward or 4 motor just forward)
L298D (like L293D but he support more Amp and Vol
L293D Adafruit shield(4 motor)
...

Here is an example for L293D:
enable PWM(0-255), inputs digital(0-1).
Motor1 : Input1, Input2, Enable1,2
Motor2 : Input3, Input4, Enable3,4

void motor1RotationDirection(int input1arg, int input2arg){
    digitaleWrite(input1, input1arg);//  LOW  |  HIGH
    digitaleWrite(input2, input2arg);//  HIGH |  LOW
                                     //Forward|Backward
}

void motor1speedRotation(int speed){
    analogWrite(enableMotor1, speed);
}    //for motor2 is the same.


How do I give the ENTER keypress? I have a Teensy set up as a keyboard, joystick, and I'm giving keyboard commands. Letter and number keys are going fine. But when I try sending ENTER, I get some extra code in my Linux terminal:

$ 16424
16424: command not found

the code I have to give the ENTER key goes like this:

void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  // read the digital inputs and set the buttons
  Joystick.button(1, digitalRead(0));
  Serial.println(digitalRead(0));
  if(digitalRead(0)==0){
    Keyboard.println(KEY_ENTER);
  }
  delay(50);
}

where is this  "16424" coming from, and how do I send an ENTER keypress?
I am using a Teensy 2.0, on Linux, with Arduino IDE 1.6.7.

You can't just "print" a key like that. You use print for sending text.

When you use println it sends an enter key along with your text, so you can do :

Keyboard.println("ls -al");

and it will send the text ls -al and press enter for you.

If you want to do it in the 'raw' way you will need to press and then release the key:

Keyboard.press(KEY_ENTER);
Keyboard.release(KEY_ENTER);


How do I power a linear actuator at different speeds for specified periods of time I am new to Arduino and wondering if anyone can help me get it programmed correctly. I am using two buttons to control a linear actuator to open and close a barn door. I want it to go a certain speed for a specified period of time... like 3 seconds. Then I want it to slow down and go another 2 seconds. The linear actuator does not have feedback which is fine for the application because it does not have to be precise. Below is the code I copied from the manufacturers website - it works well, but I can’t figure out how to make it go for specified periods of time. Please remember I’ve never used an Arduino before and this is literally a foreign language to me. I’m just hoping someone can tell me what to do. It’s for my house, not for a school project.
*** ADDENDUM - Thanks for the help. Wish I could post a video... Here is the final code:
/* Firgelli Automations
 * Limited or no support: we do not have the resources for Arduino code support
 *
 * Program enables momentary direction control of actuator using push button
 */

int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int RPWM2 = 5; //connect Arduino pin 5 to IBT-2 pin RPWM
int LPWM2 = 6; //connect Arduino pin 6 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 0; // Top speed you can change it between [0-255]
int speed2 = 0; // Low speed you can change it between [0-255]
int speed3 = 0; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(RPWM2, OUTPUT);
  pinMode(LPWM2, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(RPWM2, 0);
    analogWrite(LPWM, 255); // rotate motor with top speed (with PWM set to 255)
    analogWrite(LPWM2, 236); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for x sec
    analogWrite(LPWM, 185); // rotate motor with low speed (with PWM set to 150)
    analogWrite(LPWM2, 181); // rotate motor with low speed (with PWM set to 150)
    delay(1600);               // wait for x sec
    analogWrite(LPWM, 80); // rotate motor with low speed (with PWM set to 150)
    analogWrite(LPWM2, 80); // rotate motor with low speed (with PWM set to 150)
    delay(1400);               // wait for x sec
    analogWrite(LPWM, 0);     // uncomment if you want to stop motor now
    analogWrite(LPWM2, 0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(LPWM2, 0);
    analogWrite(RPWM, 254); // rotate motor with top speed (with PWM set to 255)
    analogWrite(RPWM2, 255); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for x sec
    analogWrite(RPWM, 170); // rotate motor with low speed (with PWM set to 150)
    analogWrite(RPWM2, 170); // rotate motor with low speed (with PWM set to 150)
    delay(1500);               // wait for x sec
    analogWrite(RPWM, 80); // rotate motor with low speed (with PWM set to 150)
    analogWrite(RPWM2, 80); // rotate motor with low speed (with PWM set to 150)
    delay(1500);               // wait for x sec
    analogWrite(RPWM, 0);     // uncomment if you want to stop motor now
    analogWrite(RPWM2, 0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
    analogWrite(RPWM2, 0);
    analogWrite(LPWM2, 0);
  }
}

You can do this easily by using Arduino built-in PWM function and using delay function. But remember that using delay in your code will block your code so if your program just want to sit and wait for 3 seconds at some speed then delay is ok for you else you need to implement Millis function.
first you need to define different speeds as per your requirement remember PWM function has value from 0-255 where 0 in min speed and 255 is top speed.
So here I will define speed1 for top speed and speed2 for low speed
So now your program will look like this
int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 255; // Top speed you can change it between [0-255]
int speed2 = 150; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(LPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(LPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
   // analogWrite(LPWM,0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(RPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(RPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
    // analogWrite(RPWM,0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
  }
}


What do these pins on the Uno do? I've been wondering for a long time what these pins, labeled ICSP and blank, do.

I can't seem to find a diagram that explains them, so I've been wondering:

What are they for?
Are they GPIO, or do they do something special?
How can you use them?

Thanks for the help.

They're for programming, as well as carrying the non-select signals for SPI. The right one is for programming the main MCU, the left for the USB communication MCU. You should almost never need to use them unless you need to write a bootloader to a new chip or change the fuse or lock settings on them.


how can I change the setting for number of upload retries in the IDE? I run into this problem when I mess something up, and it's pretty annoying to wait for 10 not in sync timeouts before I can try some different method.

...
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x85

How can I set the number of "attempts" to say 2 instead of 10? Or how can I safely interrupt the upload process in the IDE?

The code is not in the arduino ide but in the tool chain (.exe) that it runs.

Normally it is a program called avrdude.exe that is running so you would need to rebuild the avrdude.exe tool which is not practical.

The easiest way, but rather crude, is to pull the usb cable. If the port disappears avrdude should stop immediately.


Check the value of character variable I'm writing some code for Arduino and I'm not sure if I'm checking the value of this character variable correctly. Can you please tell me if this is correct:

const char* front = "front";
const char* back = "back";

eyeballs(front);
eyeballs(back);

void eyeballs(const char* frontOrBack){

if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);}//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);}//end else*/
}

Since you are using C strings (array of characters) instead of the C++ String class, you cannot use the == operator.

Instead, you can use the C style strcmp function, which is also part of the C++ library:

    #include <string.h>
       .
       .
       .

    if (!strcmp(frontOrBack,"front")) {
        digitalWrite(frontEyes, LOW);}//end if
    else if (!strcmp(frontOrBack,"back")) {
        digitalWrite(backEyes, LOW);}//end else*/
    }


Current mouse pointer position with Digispark attiny85 I am trying DigiMouse library for attiny85 Digispark board.

It allows to emulate the mouse quite well.
However, I also need to know the current cursor position. Is there a way to get it?

There is no way for a mouse of any kind (especially not one as minimal as DigiMouse.h) to know the current cursor position - USB just doesn't provide that kind of facility.

Instead you need to implement an "absolute" mouse (aka a "tablet").  However DigiMouse doesn't implement such a facility. So you would have to implement your own tablet driver.

A normal mouse sends a "delta" for the position. That is, a difference in position from whatever the current position is.  An absolute mouse, or tablet, sends the position on the screen as a proportion of some maximum set of dimensions.  Ideally that would be the same dimensions as your screen, but doesn't have to be.

The main differences between DigiMouse and whatever you would implement for a DigiTablet would be the "HID Report Descriptor". This defines what the data that is sent means and how the computer should interpret it.


Problem to convert rotary encoder output to angle I'm using this incremental rotary encoder with a rotating disc.

Here is my system:

I will explain the system briefly and above is the illustration for that:

The rotary encoder(blue) is attached/fixed to a larger disc(yellow) concentrically at its origin, so both the encoder and the disc rotate together the same angle.
The disc is rotating on a fixed plane(gray). The plane has a fixed point mark(red X) on its surface.
There is also a fixed red arrow on the disc.

Each time before the system is powered, I will manually rotate the disc such that its red arrow will be aligned to the red X mark on the surface.
This adjustment each time at the beginning will provide the reference point.

After this adjustment I want to output the actual angles via Arduino.

I tried the following example code from Arduino website:

#define encoder0PinA  2
#define encoder0PinB  4

volatile unsigned int encoder0Pos = 0;

void setup() {

  pinMode(encoder0PinA, INPUT);
  digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
  pinMode(encoder0PinB, INPUT);
  digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor

  attachInterrupt(0, doEncoder, CHANGE);  // encoder pin on interrupt 0 - pin 2
  Serial.begin (9600);
  Serial.println("start");                // a personal quirk

}

void loop(){
// do some stuff here - the joy of interrupts is that they take care of themselves
}

void doEncoder() {
  /* If pinA and pinB are both high or both low, it is spinning
   * forward. If they're different, it's going backward.
   *
   * For more information on speeding up this process, see
   * [Reference/PortManipulation], specifically the PIND register.
   */
  if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos++;
  } else {
    encoder0Pos--;
  }

  Serial.println (encoder0Pos, DEC);
}

/* See this expanded function to get a better understanding of the
 * meanings of the four possible (pinA, pinB) value pairs:
 */
void doEncoder_Expanded(){
  if (digitalRead(encoder0PinA) == HIGH) {   // found a low-to-high on channel A
    if (digitalRead(encoder0PinB) == LOW) {  // check channel B to see which way
                                             // encoder is turning
      encoder0Pos = encoder0Pos - 1;         // CCW
    }
    else {
      encoder0Pos = encoder0Pos + 1;         // CW
    }
  }
  else                                        // found a high-to-low on channel A
  {
    if (digitalRead(encoder0PinB) == LOW) {   // check channel B to see which way
                                              // encoder is turning
      encoder0Pos = encoder0Pos + 1;          // CW
    }
    else {
      encoder0Pos = encoder0Pos - 1;          // CCW
    }

  }
  Serial.println (encoder0Pos, DEC);          // debug - remember to comment out
                                              // before final program run
  // you don't want serial slowing down your program if not needed
}

But this code increases one count for each encoder tick at CW direction, and decreases one count for each tick at CCW direction.
It keeps increasing from zero to 65535 in CW and decrease from 65535 to 0 in CCW.
I want to translate this code such that I can output the angle in degrees.

My encoder says its ppr is 15 and 30 ticks. This code increase/decrease one count for each tick.

Any idea how to extract the angle from this setup? (It doesn't have to use the specific code I provided.)

Gerben's comment is mostly right. The shortest way to adapt the behavior of that sketch to your setup is by multiplying the result by 24 (not 12, since it is 15 pulses - 30 dents, but each channel varies 15 times) and then making the modulo:

if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos += 24;
} else {
    encoder0Pos -= 24;
}
encoder0Pos = encoder0Pos % 360;

BUT... the code you posted has some problems.

"The joy of interrupts is that they take care of themselves" is true, but relying on interrupts always has some drawbacks you MUST take into account. Mainly you are blocking the rest of the program (screwing up the timings for instance). I prefer to use the interrupts only when strictly needed (and this is not the case)
You are performing a potentially long function (serial interaction) into an interrupt. Totally wrong
You are using HALF the steps you can potentially use (since you are checking only one input, you are ignoring half the transitions).

To fix these, I propose you to rewrite the program to check in the loop the buttons status. Then, since they are mechanical switches, I'm going to use the Bounce2 library to debounce the inputs.

This, alongside with solving the previous 3 points, will also allow you to use any arbitrary pin on the board.

#include <Bounce2.h>

#define encoder0PinA  2
#define encoder0PinB  4
#define STEP_SIZE 12

byte encoder0Pos = 0;

Bounce debouncerA = Bounce();
Bounce debouncerB = Bounce();

void setup()
{
    debouncerA.attach(encoder0PinA, INPUT_PULLUP);
    debouncerA.interval(5); // interval in ms
    debouncerB.attach(encoder0PinB, INPUT_PULLUP);
    debouncerB.interval(5); // interval in ms

    Serial.begin (9600);
    Serial.println("start");                // a personal quirk

}

void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }

    if (EncVariation != 0)
    {
        encoder0Pos = (encoder0Pos + EncVariation * STEP_SIZE) % 360;

        Serial.println (encoder0Pos, DEC);
    }
}

Disclaimer: I haven't tested this, but I'm pretty confident this will work.

I highly suggest you to use the Bounce2 library, since it also has many helper functions which shorten the code a lot. See here for instructions on how to get and use it. I'm just a happy user of this library, and I'm not linked in any way to the author ;)


How to connect D1 mini and ATTINY85 over data wire I’m trying to connect my D1 mini module and attiny85 USB module together over a data wire, but I don’t know how to do it.
Basically, what I want to do is have the D1 broadcast a hotspot with a web page that when a button is pressed, it sends a signal to the attiny85. The D1 is connected via power wires to the attiny85.
I have the sending signal and web server setup on the D1 but I don’t know how to let the attiny85 receive it.
If it helps, I’m using the wire.h library on the D1
(edit: sorry for inactivity, just haven’t been able to test it)

ATTinyCore seems to come with a Wire library implementation presenting the same interface as you find in other Arduino board packages.  The damellis package doesn't, so if you've been trying to use that one, I'd suggest switching to ATTinyCore.
To get started you should be able to use the ESP8266-Arduino Wire library's Master Writer example with ATTinyCore Wire library's Slave Receiver example.  To be clear, you don't need to get them from github, they should be available in the File/Examples menu.  Because the interface is the same, you may find that it doesn't matter which board from which you take the example.
I don't know that I've ever used this Wire library in ATTinyCore; my only memory of using I2C slave no an ATTiny85 was coding it directly myself, but I expect it works fine.  I may try myself to confirm though.
On the ATTiny85 you'll be using DIP/SOIC pin 7 (PB2) for the SCL signal.  And DIP/SOIC pin 5 (PB0) for the SDA signal.
If I try it myself later I'll update this with more details.
More details
I don't have a D1 mini.  I do have this NodeMCU clone though.  According to the pin maps, the D1 mini's D1 and D2 pins are same as on the NodeMCU, that is GPIO5 an GPIO4 respectively.  I wired it together as shown here:

I've drawn some lines on the lower part of the image where the camera angle is bad.  The smaller inset images are just for showing a better angle there.  The yellow and white leads carrying I2C "Wire" data are doctored simply because they went out of frame.
Don't take the "5V" on the ISP cable breakout too literally, that line is at 3.3V (from the NodeMCU 3.3V pin).
ATTiny85 had the following code loaded onto it.  It is just the ATTinyCore slave receiver example with unnecessary comments removed and code to set the LED based on whether it receives a non-zero byte in the I2C ("Wire") transaction:
#include <Wire.h>

static const int LED_PIN = 4;
static const int SLAVE_ADDRESS = 0x08;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(wire_receive);
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {}

void wire_receive(int howMany) {
  if (Wire.available()) {
    digitalWrite(LED_PIN, Wire.read());
  }
}

The following was loaded onto the NodeMCU board.  Likewise derived from the ESP8266 Arduino Wire master-writer example.  Set the local ESP8266 led when it sends the state over to the ATTiny85.  The result is that the ATTiny85 and ESP8266 change their LEDs every 1 second together.  The NodeMCU module is wired to light the LED on a LOW, the ATTiny85 to light on a HIGH, so when one is lit the other is not.
#include <Wire.h>
#include <PolledTimeout.h>

#define SDA_PIN 4
#define SCL_PIN 5
const int16_t I2C_SLAVE_ADDRESS  = 0x08;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin(SDA_PIN, SCL_PIN);
}

void toggle_led() {
    static bool led_state;

    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Wire.write(led_state);
    Wire.endTransmission();
}

void loop() {
  using periodic = esp8266::polledTimeout::periodicMs;
  static periodic nextPing(1000);

  if (nextPing) {
    toggle_led();
  }
}


HTTP Post data from Arduino uno using WiFi Please help me to post data from arduino uno to a webpage using wifi(ESP-01) module. I try with AT commands it didn't give the response from my webpage

#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#define DEBUG true

#define RX 10
#define TX 11
String WIFI_SSID = "*****";       // Your WiFi ssid
String PASSWORD = "*****";         // Password
//String DEVICE_SECRET_KEY  = "**";

//String PATH = "/v1/events";
//String PORT = "8000";
//String HOST = "http://10.**.***.66:8000/data";

String HOST = "10.**.240.**";
String PATH = "/data";
String PORT = "8000";

String response;
int countTrueCommand;
int countTimeCommand;
boolean found = false;

SoftwareSerial esp8266(RX, TX);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200);
  esp8266.println("AT");
  Serial.println(esp8266.read());
  sendCommandToESP8266("AT", 5, "OK");
   sendCommandToESP8266("AT+CWMODE=3", 5, "OK");
  sendCommandToESP8266("AT+CWJAP=\"" + WIFI_SSID + "\",\"" + PASSWORD + "\"", 20, "OK");
}

void loop()
{
  root["key"] =  "sdfsdfsd";
  String key;
  root.printTo(key);
  String postRequest =   "POST " + PATH  + " HTTP/1.1\r\n" +
                         "Host: " + HOST + "\r\n" +
                         "Accept: *" + "/" + "*\r\n" +
                         "Content-Length: " + key.length() + "\r\n" +
                         "Content-Type: application/json\r\n"
                         "\r\n" + key;
  Serial.print("pst:" + postRequest);
  sendCommandToESP8266("AT+CIPMUX=1", 5, "OK");
  sendCommandToESP8266("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  String cipSend = "AT+CIPSEND=0," + String(postRequest.length());//GET /test.php?Data=2\r\nHost:192.168.1.13\r\n\r\n
  sendCommandToESP8266(cipSend, 4, ">");
  sendData(postRequest);

  while (esp8266.available())
  {
    if (esp8266.find("+IPD,"))
    {
//      String msg;
      esp8266.find("?");
//      msg = esp8266.readStringUntil(' ');
      response = esp8266.readStringUntil(' ');
      Serial.print(response);
      Serial.println();
    }
  }
  printResponse;

  //  sendCommandToESP8266("AT+CIPCLOSE=0", 5, "OK");
}

void sendCommandToESP8266(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime * 1))
  {
    esp8266.println(command);
    if (esp8266.find(readReplay))
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if (found == true)
  {
    Serial.println("Success");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if (found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

void sendData(String postRequest) {
  Serial.println(postRequest);
  Serial.println();
  esp8266.println(postRequest);
  delay(15000);
  countTrueCommand++;
}

void printResponse() {
  while (esp8266.available()) {
    Serial.println();
    Serial.println(esp8266.readStringUntil('\n'));
  }
}

Please help me to get the response from the webpage using this code.

Step 1) Upload software serial from example and send AT, you should get reply as AT OK if your connections are correct.
Step 2) Once your connections are correct and if you are uploading the given code then make sure you put your SSID, password, and Server IP which would be the three Strings: HOST, PATH and PORT.

You could alternatively check your server first by sending it a GET or POST using your browser or another software for testing API's(I personally use POSTMAN).

Proceed further once you perform these checks.


Motor shield power from Arduino pro mini 5v RAW Pin 150mAh cannot run servo linked to my old question, Pro Mini 5v with Adafruit motor shield v1 power sharing problems

I figured out and use one 7.2v battery (6 AA cells), and link it with RAW pin to Pro mini and join its 5v pin to motor shield 5v. It works but as I have a servo on this shield, 2 distance sensors so servo does not work well all the times. Stops or does not move as directed, shaking etc. I figured out that pro mini output 5v but only 150mAh which is not sufficient to run a servo which while sharing same 5v for motor shield. I need to know if I want to supply 5v 2000mAh from AA cells or 5v regulator, should I use these pins on motor shield (5v, Gnd, 9v)? I tried but it did not work. I did not find it anywhere on net.

How can I use these pins shown in the picture.
What is the min/max mAh value of current I can provide at these pins?
If supplying input current at these pins, should I connect/disconnect power jumper?

I am totally stuck. Need help. And here is the quick diagram how things are attached. All other pins are attached at shield connects to UNO when stack on it.

You can't, or at least you can't do it the way you want to. Each pin can give you a maximum of 40mA. You may try using more than one pin but that possibly wont work for you. I suggest you supply additional power from a separate source and control On/Off from Arduino. It would be like a relay. Or simply buy a relay to do this.


Generate 2 PWM signals Vc and Vh from Arduino Uno I want to generate two PWM signals VC and VH to give input to the gas sensor  with the duty cycle mentioned below. I also want to take the reading from the same sensor at the same time using Arduino Uno.

[

I am confused how to proceed with the code in Arduino Uno.

You can use the millis() function to see how much time has passed and use this to create your waveform while still being able to perform other tasks. You will check in which part of the wave you are in each iteration of loop() and adjust your outputs accordingly.

E.g:

long vhtime;
uint8_t vhpin = 9;   // the VH output pin
uint8_t vcpin = 10;  // the VC output pin

long period = 250;   // the period of your pwm signal in ms
long vhduty = 14;    // amount of ms vh should be high
long vcdelay = 2;    // amount of ms we wait for vc to go high after vh has gone high
long vcduty = 5;     // amount of ms vc should be high

long curtime;        // this will hold our current position in one period of the waveform

void setup() {
  pinMode(vhpin, OUT);
  pinMode(vcpin, OUT);
  digitalWrite(vcpin, LOW);
  digitalWrite(vhpin, HIGH);
  vhtime = millis();
}

void loop() {
  curtime = millis() - vhtime;
  if (curtime > vhduty)        // we are in the last 236ms of the wave, vh should be low
    digitalWrite(vhpin, LOW);
  else                         // we are in the first 14ms of the wave, vh should be high
    digitalWrite(vhpin, HIGH);
  if (curtime > vcdelay && curtime < vcduty + vcdelay) // vc should be high during this time
    digitalWrite(vcpin, HIGH);
  else
    digitalWrite(vcpin, LOW);
  if (curtime > period) {
    // we should start a new period
    digitalWrite(vhpin, HIGH);
    vhtime = millis();
  }
  // do your other calculations here
}


Ultrasonic Sensor scanning too often resulting in a whirring noise I am using an HC-SRO4 ultrasonic sensor for a wall-avoidance, maze-solving robot. However, I have recently run into an issue where I am getting a whirring noise from the sensor because it is taking measurements way too often.

This is the code I have right now:

const int serialPeriod = 250;       // only print to the serial console every 1/4 second
unsigned long timeSerialDelay = 0;

const int loopPeriod = 20;          // a period of 20ms = a frequency of 50Hz
unsigned long timeLoopDelay   = 0;

// specify the trig & echo pins used for the ultrasonic sensors
const int ultrasonic2TrigPin = 8;
const int ultrasonic2EchoPin = 9;

int ultrasonic2Distance;
int ultrasonic2Duration;

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

    // ultrasonic sensor pin configurations
    pinMode(ultrasonic2TrigPin, OUTPUT);
    pinMode(ultrasonic2EchoPin, INPUT);
}

void loop()
{
    debugOutput(); // prints debugging messages to the serial console

    if(millis() - timeLoopDelay >= loopPeriod)
    {
        readUltrasonicSensors(); // read and store the measured distances

        timeLoopDelay = millis();
    }
}

void readUltrasonicSensors()
{
    // ultrasonic 2
    digitalWrite(ultrasonic2TrigPin, HIGH);
    delayMicroseconds(10);                  // must keep the trig pin high for at least 10us
    digitalWrite(ultrasonic2TrigPin, LOW);

    ultrasonic2Duration = pulseIn(ultrasonic2EchoPin, HIGH);
    ultrasonic2Distance = (ultrasonic2Duration/2)/29;
}

void debugOutput()
{
    Serial.print("timeSerialDelay: ");
    Serial.print(timeSerialDelay);
    Serial.println();

    if((millis() - timeSerialDelay) > serialPeriod)
    {
        Serial.print("ultrasonic2Distance: ");
        Serial.print(ultrasonic2Distance);
        Serial.print("cm: ");
        Serial.println();

        timeSerialDelay = millis();
    }
}

and my wiring:

Link to product

Does anyone know why the scanning is happening constantly? It should only be happening every 1/4 of a second, not constantly. The weird thing is that this wasn't happening earlier before I started using the cable.

I believe it has something to do with the 8.5" extension cable I have (needed because I can't mount three sensors, one facing to each side and one in front, on a single breadboard). This is because when I mounted the sensor directly onto the breadboard, the delay was correct and the whirring was not present. However, as I just mentioned, I need the extension cable to be able to have the three sensors.

Does anyone have a solution for this?

Thanks!

If you want to sample at 4Hz (4 times per second), you need to change your headers accordingly:

const int serialPeriod = 250;       // only print to the serial console every 1/4 second
unsigned long timeSerialDelay = 0;

const int loopPeriod = 250;          // a period of 250ms = a frequency of 4Hz
unsigned long timeLoopDelay   = 0;


Will 12.6v really damage my arduino? I'm using a 12v fan and 12v LED modules in my project, so I need about 400mA by their combined specs. I have a 12.6v dc regulated power source that can give ~700mA I wish to use, and since it has a rather small form factor I would also like to power my Arduino Diecimila with it. I'm using PWM from pins 10 and 6 to go through N-channel MOSFETs in order to control both the LEDs and the fan. Anyway, in the Arduino Diecimila board page it says the recommended voltages are between 7-12v, and beyond that it can handle 6-20v, but it might cause the voltage regulator to heat too much, which might damage the board. So, my question is that: will 12.6v really damage my board, or is it within some margin of error? The actual voltage I got when I checked my power supply was 12.55V. Can I maybe just dial it down a bit somehow?

Thanks in advance,

UriSh.

As you have already noticed, it may cause the 5V regulator to get hotter than would be normally considered reasonable.  However, how hot depends entirely on how much current your board is drawing (not including the 12V devices)- the more current you draw the hotter it will get.

Even at 12V it can get uncomfortably hot.

For running off voltages greater than about 9V I usually recommend using an external 5V switching regulator.  These can be easily and cheaply obtained under the name "UBEC" (Universal Battery Elimination Circuit) and are used extensively in the model aircraft arena.  They don't get hot, can handle large currents, and don't waste power like the on-board linear regulator does.

So you'd connect that to your 12.6V supply, then the 5V output of the UBEC (make sure you get a 5V one) would go straight to the 5V pin of the Arduino, and you wouldn't connect the barrel jack or Vin to anything.

You can also pick up cheap switching regulators on eBay - some are adjustable, so you'd want to make sure you adjust it to 5V first before connecting the Arduino, or if you can adjust it to around 7V then you could power the Arduino through the barrel jack (or Vin) with it and avoid too much heat from the on-board linear regulator.


4 IR sensors on Arduino pro micro. 2 are working other aren't #include <Keyboard.h>
int IRpin = 5;
int IRpin2 = 6;
int IRpin3 = 8;
int IRpin4 = 9;
int led = 13;

void setup() {
  Serial.begin(9600);
  //start the serial port
  Keyboard.begin();
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}

void loop() {
  float volts = analogRead(IRpin);
  Serial.println("volts1:");
  Serial.println(volts);
  delay(1000);
  if (volts>500.00){
    Keyboard.press(KEY_RIGHT_ARROW);
    Keyboard.releaseAll();
  }
  float voltss = analogRead(IRpin2);
  Serial.println("volts2:");
  Serial.println(voltss);
  delay(1000);
  if (voltss>600.00){
    Keyboard.press(KEY_LEFT_ARROW);
    Keyboard.releaseAll();
  }
  float voltsss = analogRead(IRpin3);
  Serial.println("volts3:");
  Serial.println(voltsss);
  delay(1000);
  if (voltsss > 500.00) {
    Keyboard.press(KEY_UP_ARROW);
    Keyboard.releaseAll();
  }
  float voltssss = analogRead(IRpin4);
  Serial.println("volts4:");
  Serial.println(voltssss);
  delay(500);
  if (voltssss > 600.00) {
    Keyboard.press(KEY_DOWN_ARROW);
    Keyboard.releaseAll();
  }
}

I connected 4 IR infrared sensors to Pro micro and only 2 of them are working. The other 2 are sending random values.
Connection for all 4 IR sensors.:
IR VCC->Arduino VCC
IR GND -> Arduino GND
Output-> 5,6,8,9

Pin 5 is not analog pins.

On the pro-micro only pins A0-5 and D4, D6, D8-10, D12 can convert an analog voltage to a value.

Just use the A0-5 pins instead, as that will work on any Arduino.


What happens, memory-wise, when I call a function from another function? I'm inspecting where the memory is used in an application which runs on Arduino. To my surprise, there are several locations where 100 to 200 bytes are consumed by simply calling a function. Example:
void Dispatcher::processCommand() {
    ...
    displayMemory();
    this->process(this->instruction);
}

void Dispatcher::process(const Instruction &instruction) {
    displayMemory();
    if (instruction.length > 0) {
        ...
        return;
    }

    ErrorResponse::componentNotFound(instruction).output(this->serial);
    TerminationResponse(instruction.commandId, 0xFF).output(this->serial);
}

The first call to displayMemory() will report that there is 351 bytes left. The second one will tell that only 159 bytes remain (that is, 192 bytes less).
If I alter the body of the process function, the difference between the two memory reports vary. For instance, if I remove the two last lines, the difference drops from 192 bytes to 12 bytes.
I don't understand why this happens. I was thinking that between the moment I'm ready to call a function and a moment when the function starts, the memory should be used exclusively by the additional element in the call stack (the aforementioned 12 bytes maybe?) and the copying of the parameters passed by value (none here). Why is this not the case? What really happens under the hood?

The clue is in those last two lines:
    ErrorResponse::componentNotFound(instruction).output(this->serial);
    TerminationResponse(instruction.commandId, 0xFF).output(this->serial);

Let's tear them apart and see what they actually do.
ErrorResponse::componentNotFound(instruction).output(this->serial);

Call the static function componentNotFound with your instruction, then take the object that is returned, and call the output() method on it passing this->serial as a parameter.
The hint there is take the object that is returned.
componentNotFound() returns an object. That object has to be stored somewhere. That "somewhere" is on the stack.  And stack space is allocated during the function preamble.  That's the bit of code that runs at the start of the function allocating stack, pushing registers to the stack, etc.
The same happens in the second line:
TerminationResponse(instruction.commandId, 0xFF).output(this->serial);

Create a new TerminationResponse object and call the output method.
All that goes on the stack.
It's not the calling of the function that is using the memory, it's what the function is doing that is using the memory.


SIM800L module on Arduino nano I am trying to get Arduino nano and SIM800L module working together. I provided the module with the recommended external voltage of 4.0V (documentation states 3.6V - 4.2V) transformed via LM2596. The original source is 5V 3A.
LED on SIM800L blink once a second as stated in documentation when in an unconnected state.
The schema is the following:
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
D2 --------- RST
D3 --------- RX
D4 --------- TX
             GND ----- GND

I have already tried 3 different libraries for AT communication and also sending raw AT commands using writing to serial manually. I also tried another SIM800L module because I thought the module is faulty.
Here is the dump from serial communication:
[551135] ### TinyGSM Version: 0.10.9
[551139] ### TinyGSM Compiled Module:  TinyGsmClientSIM800
AT
��AT
�AT
H�j���[552012] ### Unhandled: Hj
AT
AT-���[552317] ### Unhandled: AT-
AT
��AT
��AT
�Z5
[553228] ### Unhandled: Z5
AT
␚)O���[553532] ### Unhandled: ␚)O
AT
AT���[553836] ### Unhandled: AT
AT
��AT
��AT
�)OK��[554748] ### Unhandled: )OK
AT
���[555053] ### Unhandled: 5
AT
���AT
��AT
��AT
�j�H�[556266] ### Unhandled: jH
AT
CC����[556570] ### Unhandled: CC
AT
AT���[556875] ### Unhandled: AT
AT
��AT
AT
���[557787] ### Unhandled: T
AT
�H����[558091] ### Unhandled: H
AT
AT���[558395] ### Unhandled: AT
AT
��AT
��AT
AT
jRO���[559610] ### Unhandled: jRO
AT
AT���[559915] ### Unhandled: AT
AT
��AT
��AT
AT
�
OK��[561128] ### Unhandled: OK
Failed to initialize SIM800L

As you can see the module is trying to negotiate the baudrate. By default, I use speed 9600 as stated in the documentation. When I use a different baudrate the module does not respond at all.
It seems the module replies and sometimes even correctly. Response to AT command should be OK.
Do you know how do I successfully negotiate the speed and establish reliable serial communication with the module? Do I miss any electrical components in my circuit like a capacitor or resistor? I tried to use capacitor 35V / 3300µF but without any difference. I think my power source is strong enough.
The source code is the following:
#define PIN_GSM_RST             2
#define PIN_GSM_TX              3
#define PIN_GSM_RX              4
#define GSM_BAUDRATE            9600

#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_DEBUG          Serial
#define TINY_GSM_USE_GPRS       true
#define TINY_GSM_USE_WIFI       false

#include <Arduino.h>
#include <SoftwareSerial.h>
#include <TinyGsmClient.h>
#include <StreamDebugger.h>

SoftwareSerial serial_SIM800L(PIN_GSM_RX, PIN_GSM_TX);
StreamDebugger debugger(serial_SIM800L, Serial);
TinyGsm modem(debugger);
TinyGsmClient client(modem);

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

    Serial.println(F("Serial initialized"));

    serial_SIM800L.begin(GSM_BAUDRATE);
    delay(5000);

    while (!modem.init()) {
        Serial.println("Failed to initialize SIM800L");
    }
}

void loop() {
    //
}

Thanks to @PeterPaulKiefer here is the answer.
External power for SIM800L module GND pin needs to be connected to both SIM800L module GND pin and Arduino nano GND pin. (e.g between RST and R2 pin on Arduino nano)
In order for the calling function to work, you also need to use a capacitor on SIM800L VCC and GND pins. I used 35V, 3300µF.
Schema:
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
 D2 --------- RST   |
 D3 ---------  RX  === Capacitor (35V, 3300µF)
 D4 ---------  TX   |
GND --------- GND ----- GND


Blink LED with different on off times just once with millis So Im having trouble trying to figure this out. My project needs a valve to stay shut and when an event is triggered, 3 seconds into that event the valve opens for 2 seconds, then remain shut till it's triggered again. I was just treating it like an LED in the code. I was trying to code it to jump from one if-statement to the next with the appropriate delays but it doesn't work the way i thought it would. Any help would be great. Thanks
//the event does ventGo0 = true;

 if(((millis() - previousVenting) > offoffDuration)&&(ventGo0==true)){
        previousVenting1 = millis();
        ventGo1=true;
        ventGo0=false;
       }

     if(((millis() - previousVenting1) > onDuration)&&(ventGo1==true)){
       digitalWrite(ventPin, HIGH);
       previousVenting2 = millis();
       ventGo2=true;
       ventGo1=false;
     }

       if(((millis() - previousVenting2) > offDuration)&&(ventGo2==true)){
         digitalWrite(ventPin, LOW);
         ventGo2=false;
       }

      ```

You could use two millis() based timers.
// Sketch uses 1066 bytes (3%) of program storage space.
// Global variables use 27 bytes (1%) of dynamic memory.
// Arduino Uno, IDE 1.8.9
class MillisTimer{

  private:

    unsigned long m_timeInMilliSeconds;
    unsigned long m_previousMillis;
    byte m_timerActive;

  public:

    MillisTimer(unsigned long timeInMilliSeconds):
      m_timeInMilliSeconds(timeInMilliSeconds){
      m_timerActive = 0;
      m_previousMillis = 0;
    }

    bool Update(){
      if(m_timerActive && (millis() - m_previousMillis >= m_timeInMilliSeconds)){
        m_previousMillis += m_timeInMilliSeconds;
        return 1;
      }
      else{
        return 0;
      }
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_previousMillis = millis();
    }

    byte IsActive(){
      return m_timerActive;
    }

};

// Make copies of the object to work with.
MillisTimer TwoSecondTimer(2000);
MillisTimer ThreeSecondTimer(3000);

void setup(){

  // Call this function when an event is triggered.
  ThreeSecondTimer.ReStart();

  // Timer status indicator.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // Call the update function as fast as possible.
  if(ThreeSecondTimer.Update()){
    digitalWrite(LED_BUILTIN, HIGH);
    ThreeSecondTimer.Stop();
    TwoSecondTimer.ReStart();
  }

  // Call the update function as fast as possible.
  if(TwoSecondTimer.Update() && !ThreeSecondTimer.IsActive()){
    digitalWrite(LED_BUILTIN, LOW);
    TwoSecondTimer.Stop();
  }

}


Connecting Function Generator to Arduino I want to send a function generator's signal to an Arduino UNO Analog pin. Can I use an Oscilloscope probe connected to the function generator output BNC, set to 1x to connect to the Arduino headers using jumper wires? I did read through the manuals of the function generator, but couldn't find a solution.

The function generator available is Tenma 72-14110.

Sure, you can connect the function generator to an analog pin of the Arduino. The probe and the jumper wires are just wires here, nothing special. You should also connect the function generators ground to the Arduinos ground (!).

But: Be sure to stay in the Arduinos voltage range (0 to 5V) with the function generators signal. If you apply a higher or negative voltage, you can destroy the Arduino. As long, as you stay inside that range, nothing bad will happen.


Arduino Leonardo on Win 8.1 COM port disappeared I've been using an Arduino Leonardo on my Windows machine for a few days now without too much trouble but today the COM port disappeared. I've been able to successfully send sketches to the arduino and execute them so everything was working until recently. When I look in Device manager on the control panel there is no com port listed for the arduino. If I reset the device then a com port shows up briefly with "Arduino Leonardo BootLoader" but after a few seconds that disappears. I've tried USB2.0 and USB 3.0 ports on my PC and a different cable but to no avail. I don't have anything listed under "Other Devices" and I'm out of ideas for what could be the trouble.
I'm trying to get it recognised now as just the leonardo with nothing connected to any pin. Any ideas of what to try?

Strange, it's resolved itself/I resolved it. I don't know whether what I did was actually responsible for solving this but I'm back in business:
* I reset the board so that the bootloader appeared as a com port
* I set the arduino IDE to use the port that appeared for the bootloader
* I uploaded a simple sketch and pressed reset during the "upload phase" so that the port appeared during the upload
* the upload completed successfully and the arduino was back in the com port list

I'd still be interested to understand what I did that caused the problem in the first place but I suppose something was corrupted on the board?


Calculate power requirement for 64 rgb led ws2812b Hi I am working on small project where I want to run ws2812b module via arduino and lipo battery. I have purchased 64 matrix for ws2812b from eBay and lipo battery with 500mah.

I am looking to find how I can calculate how much power does WS2818b modules will consume with all leds running and will the battery be sufficient for it. How long will it run on full charge.

Can someone please point me to the formula how I can calculate this. Also to note I am using a power up converter from 3.7 to 5v.

If all LEDs are in full bright white, assume 60mA per LED. 64 would mean a maximum current draw of 64*60mA=3840mA. This figured would not include the Arduino itself.

a 500mAh battery could power this for no more than 7.8 minutes (500mAh / 3840mA = 0.17 hours = 7.8 minutes)

If your usage will not be full bright 100% if the time, then you could run longer.

You didn’t say how long you want it to run. Perhaps start with the design goal before specifying parts.

For a more realistic view of how much power it takes, measure with a multimeter the current draw from the battery or bench power supply to your boost converter while displaying a typical usage on the matrix. Use calculations as above to determine the expected battery lifespan.


Battery life with Nano v3 Easy secret knock detector to trigger anything with only an Arduino and a few cheap components

First of all I need to state that I'm new to Arduino and electronics in general. My question is about a project where the Nano is being powered up with a 12v rechargeable li-ion 2800 mAh battery on pins VIN and GND.

I'm using the 5v Nano pin to power a SRD-05VDC-SL-C relay along with the ground pin from the Nano. The IN pin on the relay is from the D11 pin on the Nano. So far so good. I'm also using the same 12v battery to power up a solenoid latch, which energizes for just a few seconds.

When I tested this setup (less the relay AND solenoid) for battery life, my volt meter read 9.8v and 1 hour later 2.8v. causing the Nano to go off.

How can I increase battery life?

This is the link to the code I used:

I'm not having an issue with the code or the operation of the setup but the battery life is unacceptable.

Something is wrong with your setup. I don't have a Nano to hand to test, but it would consume similar current to a Uno (probably less) which is around 50 mA. Thus, using a 2800 mAh battery you should have a life of 2800/50 = 56 hours.

Li-ion batteries come in multiples of cells, where individual cells have a nominal voltage of 3.6V (thus you probably have three cells giving 10.8V). Deeply discharged they will have a voltage of 3.0V per cell (a total of 9V for your three cells). If you started at 9.8V as you stated, then the cells would have been 90% discharged already which probably accounts for the short running time.

Assuming you haven't wired it in a strange way (and it would help to show the wiring and possibly a photo) I suggest you try with a fully-charged battery.

Another helpful thing to do would be to measure the current consumption of the battery using a multimeter. Make sure you read up on how to measure current with a meter or you may damage something (example here).

The basic idea is shown in this photo:

The meter is placed in series with the battery and the Arduino. The negative side of the battery goes to the Arduino in the usual way. The positive side of the battery goes into the "milliamps" input of the meter (which is set to 200 mA range in my case) and then the common (black) lead from the voltmeter goes to the positive (Vin) side of the Arduino.

You can see that in this particular case, with a 9V battery, the Arduino is consuming 57.7 mA.  I don't quite believe that reading as re-measuring with a more expensive meter gave a reading of 51.1 mA. Still, that gives you a ball-park figure. And it shows that spending a bit more on a better meter gives you more accurate results. :)

I have a page about power saving and you can also refer to the Wikipedia page about Li-ion batteries.

  my volt meter read 9.8v and 1 hour later 2.8v. causing the Nano to go off.

For a 12V Li-ion battery get down to 2.8V there is something seriously wrong with its protection circuitry. It should cut the battery out at 3V per cell, that is at 9V if you have 3 cells in series.


[SOLVED]SIM7600 Module Power up by Arduino Uno doesn't work Am using SIM7600X 4G HAT with Arduino Uno
I follow to manual to Power up the module and it works well, The NET light flashing.

But when I connect to Arduino Uno and use DigitalPin 2 write (High -> Delay500ms -> Low) for "power on pulse" it doesn't work, The NET light still not flashing.

My code:
#include <Waveshare_SIM7600.h>
// Pin definition
int POWERKEY = 2;

char phone_number[] = "XXX";      //Store the phone number you want to call

void setup() {
  Serial.begin(9600);
  sim7600.PowerOn(POWERKEY);
  sim7600.PhoneCall(phone_number);
}

void loop() {

}

code from Waveshare (Waveshare_SIM7600.h):
/**************************Power on Sim7x00**************************/
void Sim7x00::PowerOn(int PowerKey = powerkey){
   uint8_t answer = 0;

  Serial.begin(9600);

  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0)
  {
    Serial.print("Starting up...\n");

    pinMode(PowerKey, OUTPUT);
    // power on pulse
    digitalWrite(PowerKey, HIGH);
    delay(500);
    digitalWrite(PowerKey, LOW);

    // Stuck in below loop because Send AT command and no response ///////
    // Becuase NET light not flashing (not connect) //////////////////////

    // waits for an answer from the module
    while (answer == 0) {     // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
      delay(1000);
    }

  }

  delay(5000);

  while ((sendATcommand("AT+CREG?", "+CREG: 0,1", 500) || sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0)
    delay(500);
}

The GSM module requires a 5V 2A source and my Arduino Uno cant draw for it, my solution is to use a power bank that can draw 5V 2A for powering the GSM module and jump PWR pin to GND (manual said) the NET led start flashing and module can working but TX, RX pin still there for comm.


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

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

and also

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

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

EDIT This command worked for me

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

Try uploading the blink sketch to the standalone atmega328 first.

Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings).


How can I see if volume buttons of Apple earphones are pressed? I need to be able to see if the volume controls and the middle button of Apple earphones are pressed.

I am using an Arduino Uno. I was thinking about using the analogRead function.

I tried connecting the ground of the audio jack to the ground of the Arduino, the micro of the audio jack to the analogPin 0 on the left and right of the audio jack to the 3.3 volt output of the Arduino, but the results of the analogRead are not really useful. They are constantly changing.

So guys i have this code that constantly gives a bunch of numbers. They are never constant.

int analogPin = 0;
int ledPinBlue = 8;
int ledPinRed = 9;

int val = 0;
int times = 0;
int clickTimes = 0;

void setup()
{
  pinMode(ledPinBlue, OUTPUT);
  pinMode(ledPinRed, OUTPUT);
  times = 0;
  Serial.begin(9600);
}

void loop()
{
  val = analogRead(analogPin);
  if (val == 0) {
times = times + 1;
  }
  else if (!val == 0) {
times = 0;
  }
  if (times == 500) {
times = 0;
digitalWrite(ledPinBlue, HIGH);   // sets the LED on
delay (500);
digitalWrite(ledPinBlue, LOW);    // sets the LED off
Serial.println("Click");
  }
}

When I press the button of the microphone (the middle button) of the apple earphones, the numbers change to a constant 0.

But when I press the volume buttons, nothing seems to change. Any ideas?

Here is an article that explains the inner working of the Apple headphones:

http://tinymicros.com/wiki/Apple_iPod_Remote_Protocol


How can I learn to use Generic ESP8266 boards Libraries in Arduino? I am new to ESP8266. I am using the Arduino IDE to program the ESP8266-01 module. How can learn to make my own codes for ESP using Arduino?

I am going through the example programs and learning which part of the code does what. But, is there a better way to understand the syntax of those libraries.

Thanks!!

They publish a reference page for the included libraries at each release of the ESP8266 core for Arduino. The latest at this time is here:

http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html

You can adjust that URL for the release version you're using.

The libraries try to follow the API of the standard Arduino libraries and that documentation mostly focuses on the differences. So you will also find some documentation for these libraries in Arduino's library reference pages:

https://www.arduino.cc/en/Reference/Libraries

and the reference pages for the Arduino core API:

https://www.arduino.cc/en/Reference/HomePage

Of course the definitive (albeit less beginner friendly) reference will always be the source code. There are two ways to quickly determine the location of the source code for a library:

Option 1:

Select the appropriate board from the Tools > Board menu. The Arduino IDE may select the library to be used based on which board is selected.
File > Examples > {library name} > pick any example
Sketch > Show Sketch Folder. This will open the {library name}/examples/{example name} folder. The source files for the library will be found in the library root folder, src folder, or utilities folder.

Option 2:

File > Preferences > Show verbose output during: > compilation (check) > OK
Write or open a sketch that includes the library.
Sketch > Compile/Verify
Wait for the compilation to finish.
Examine the contents of the black console window at the bottom of the Arduino IDE window. The path to any library used by the sketch will be found in that output.


Compiling with -flto and -nostartfiles results in no program at all Towards developing my own bootloader I've stumbled over an issue with avr-gcc. I am trying to compile my code with the compiler flags

-flto          #to enable link time optimization
-nostartfiles  #to omit the interrupt vector table

My bootloader consists of multiple files which are used depending of compile flags. All the sources are being compiled and linked while the code path only leads to some portions of them. So I wanted to get rid of the dead code and -flto (being a newer development) creates a much smaller machine code size than -ffunction-sections -fdata-sections with -Wl,--gc-sections -Wl,--print-gc-sections.

But when it comes to further reducing the machine code size by removing the interrupt vector table using -nostartfiles, the complete code gets optimized away leaving me with a zero byte output.

Has anyone experienced the same issue with that compiler flag combination?

As @MaximilanGerhardt wrote in his comment. LTO was optimizing away too much of the code. Usual programs start with the interrupt vector table that in case of a regular reset or startup point to the main function. That is why the compiler knows that main has an entry point and is used. The actual program starts at the table.

Removing  the interrupt vector table with -nostartfiles causes the compiler not to know that main is used at all and optimizes it away.

To give the compiler a hint __attribute__((used)) has to be placed at all methods that have to stay and there is no code path leading to them otherwise.


Arduino Mega read data from USB I´m completely new to the arduino and not used to work with it. Due to an project I need to know the best way to transfer Data to my Arduino Mega. The transferred file will be an sliced 3D object. Is it possible to use the built in USB port to read from a stick? Or do I have to use a PC to transfer my data?
Please help me to answer this question since I have no clue how to manage to get the sliced file to my Arduino.

The Arduino Mega doesn't support USB-host, so you can't connect a USB stick directly.

The easiest way is to connect it to a computer, and send the data over the serial connection.


Replacing the Voltage regulator of a fried Arduino I accidentally fried my Arduino. I found this Instructable. The symptoms are the same. The board not powering on connecting USB source and the over current protector was heating up. So I removed the voltage regulator as mentioned in the Instructable. But the problem is the pins 1 and 2 of where the regulator used to be are still shorted out. That is even after removing the regulator, the pins seem to be somehow internally shorted. I tried checking the continuity on another working Arduino and found it to be not shorted. What seems to be the problem?

I know it's an old thread, but others are likely to have this problem.  If you check the open source schematics, there are a couple of nearby capacitors that connect pin 1 (GND) to pin 2 (+5V) of the regulator.

I would check C2 and PC2 (top right of the diagram) as well as C1 (top left of schematic diagram), and any other components you can find that bridge the rails between +5V and ground.  Capacitors are more likely to fail shorted than many other components.  You will have to remove at least one pin of each capacitor to test it since you don't know where the short is, or you can simply remove capacitors until the short goes away.


How do I stop the Arduino TX/RX LEDs from flashing? How do I turn off the "ON" LED? I actually have a SparkFun RedBoard, but I think this question applies to Arduino Uno and other boards as well.

I'm wondering how much control the programmer has over the various LEDs on the board. First there's the "ON" LED which is very bright. Can this be turned off or dimmed, or do I need to resort to electrical tape?

More annoying is the "TX" and "RX" LEDs. These blink rapidly when data is being communicated over the USB-serial connection. I'm guessing these are not configurable, but I couldn't find the answer anywhere online.

I know that the "Pin 13 LED" can be controlled (via Pin 13!).

I'm wondering how much control the programmer has over the various LEDs on the board. First there's the "ON" LED which is very bright. Can this be turned off or dimmed, or do I need to resort to electrical tape?

Remove it, remove the resistor inline with it, or cut the track powering it. Either that or resort to electrical tape (or blu-tack). You have absolutely no control over it.

  More annoying is the "TX" and "RX" LEDs. These blink rapidly when data is being communicated over the USB-serial connection. I'm guessing these are not configurable, but I couldn't find the answer anywhere online.

If your board uses an ATMega16U2

As above, or compile a custom version of the ATMega16U2 firmware and flash it on to the ATMega16U2 chip.

If your board uses an FT232 chip

Download the FT232 EEPROM editing program from FTDI and use that to reconfigure the IO pins the LEDs are attached to so they do nothing. If you are on Linux you can use libftdi's ftdi_eeprom program.


What is the best way to power the ESP32 from a battery? I am making a temperature sensor that can go in a freezer and I am trying to figure out what the best method is.
My research has taken me all over the place an I can't seem to find a straight answer. Some sites recommend using LiFePo4, while others say absolutely not, because it needs to be regulated.
One question I have is: could I use more voltage, say 6V from a series of batteries and connect it to the 5V pin since it is regulated, or is it better to go with an external regulator for the 3.3V pin with less voltage?

Since it is a freezer (operating temperature unknown) I am assuming it is connected to the mains why not do the same with the electronics. This will save you a lot work and time and when you find out it will not work in a  Faraday cage as stated by timemage.  Leave the sensor wire long enough to mount the electronics outside just in case. Also consider packaging, it will be cold, possibly below the operating range of some of the components requiring you to keep them warm (above minimum temperature). I would assume your freezer like ours has moisture concerns as ice will form when opened then removed by a defrost cycle. You will also have to protect for that. Then there is the operating temperature range of the batteries, are they capable of operating at your freezer temperatures. I would suggest you redefine your problem before starting the design, this process saves me a lot of grief.


Will Nodemcu support 4AAA Will Nodemcu support 4AAA batteries which is 6v approx, or should i go with 3AAA batteries which is 4.5V approx. And one more question , is it ok to use AA instead of AAA ?

Yes, yes and yes.

  Will Nodemcu support 4AAA batteries which is 6v approx

Yes, it will. However there is no back-powering protection on the USB, so having that connected whilst the board is connected to your computer could potentially damage your computer's USB port. That's why VIN's label was changed to 5V on the newer boards.

  or should i go with 3AAA batteries which is 4.5V approx.

Yes, you should. Not only does that mean your USB port won't die, but you're not wasting as much power. The NodeMCU employs a linear "LDO" regulator to get 3.3V from the incoming power source. That means that the voltage difference between incoming power and 3.3V is thrown away as heat. The higher the incoming voltage the more heat is generated to discard that voltage.  Using a lower voltage, therefore, means that you don't waste as much. That fourth battery is doing absolutely nothing towards powering your project and is just being used to generate more heat.  One thing to note though is that 5V coming in from USB could try and charge your 3xAAA batteries. If they're not rechargeable then they could cause problems (overheat, leak, cause a fire, etc).  Adding a schottky diode in series with them would protect them from that.

  is it ok to use AA instead of AAA ?

Yes. Your project will last longer before you need to replace the batteries, since AA batteries have a higher mAh capacity than AAA.


Arduino LCD Display drawing image issue I am playing with 3,5" (400x240) TFT display which is placed into Arduino Mega 2560 R3 board.

My final goal is taking .raw data from SD card and drawing it on display.

What I have done so far:

- My drawing method in the sketch:

void LoadImage(File& file)
{
    for (int y = 0; y < SCREEN_HEIGHT && file.available(); y++) {
        uint16_t buf[SCREEN_WIDTH];
        for (int x = SCREEN_WIDTH - 1; x >= 0; x--) {
            byte l = file.read();
            byte h = file.read();
            buf[x] = ((uint16_t)h << 8) | l;
        }
        myGLCD.drawPixelLine(0, y, SCREEN_WIDTH, buf);
    }
}

- For reference drawPixelLine method's implementation from UTFT library:

void UTFT::drawPixelLine(int x, int y, int sx, uint16_t* data)
{
    unsigned int col;
    cbi(P_CS, B_CS);
    setXY(x, y, x+sx-1, y);
    for (int tc=0; tc<sx; tc++)
    {
        char* p = (char*)&data[tc];
        LCD_Write_DATA(*(p + 1), *p);
    }
    sbi(P_CS, B_CS);
}
void UTFT::setXY(word x1, word y1, word x2, word y2)
{
    if (orient==LANDSCAPE)
    {
        swap(word, x1, y1);
        swap(word, x2, y2)
        y1=disp_y_size-y1;
        y2=disp_y_size-y2;
        swap(word, y1, y2)
    }
        LCD_Write_COM(0x2a);
        LCD_Write_DATA(x1>>8);
        LCD_Write_DATA(x1);
        LCD_Write_DATA(x2>>8);
        LCD_Write_DATA(x2);
        LCD_Write_COM(0x2b);
        LCD_Write_DATA(y1>>8);
        LCD_Write_DATA(y1);
        LCD_Write_DATA(y2>>8);
        LCD_Write_DATA(y2);
        LCD_Write_COM(0x2c);
}

My current rendering:

Desired image:

TFT Lcd and Mega Board

UPDATE1

I ran henningan test from utft library, drawing sin/cos graph and simple squares

Here is attempt to render yellow square 100x100 raw data

I'have the same LCD from mcufriend and it doesn't work with original UTFT library.

Try modified version from https://github.com/dgolda/UTFT and use:

myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com


How precise is the timing of pulseIn()? I've been using the pulseIn() function for processing PWM-based binary data encoding. It works well for distinguishing pulses which are significantly different lengths, e.g. 500us vs. 1500us. That makes it more than sufficient for handling typical IR remotes.

However, I want to make my own IR system which can use more than 2 pulse lengths, so that data transfer can occur faster. Ideally, I'd like to use 8 different pulse lengths for octal encoding (e.g. 200us, 400us, 600us, etc.).

I've noticed quite significant variations in the values returned by pulseIn() though (+/- 10%). I expect at least some of it is introduced by the IR transmitter and receiver modules, but I don't have good enough equipment to verify that.

Assuming I can mitigate that external error, is pulseIn() likely to be precise enough to distinguish such similar pulses?

The pulsein() function is very lossy, in that it is a hard loop and returns a number * the assumed clock cycles it takes for per loop

...
// wait for the pulse to stop
while ((*portInputRegister(port) & bit) == stateMask) {
  if (numloops++ == maxloops)
    return 0;
  width++;
}

// convert the reading to microseconds. The loop has been determined
// to be 20 clock cycles long and have about 16 clocks between the edge
// and the start of the loop. There will be some error introduced by
// the interrupt handlers.
return clockCyclesToMicroseconds(width * 21 + 16);

The most accurate method for capturing the timing of a PIN is use the INPUT CAPTURE FEATURE. Look at the this example . It enables the input capture at 1x of CPU for max resolution and each edge of the input pin captures the timer's clock value for reading from the generated Interrupt service. It also enables the timer overflow interrupt to as to maintain large absolute time, to be capture. Since the 1x will roll rather quickly. The captures store the time into an array for reading by the main loop.

Where for signals over IR the typical library to use is shirriff/Arduino-IRremote library. Where it has several demo's that will read and send the IR from a demodulated signal. To allow one to build a sketch of their own design. This code originally creates a timer interrupt that polls the input pin at a rate determine by

#define USECPERTICK 50  // microseconds per clock interrupt tick

in the IRremote.h file. For my purposes I have change it to 25 us. Where I find this still can be intermittently missing pulse streams.

Note the demodulation is best accomplished within the IR receiver, which in turn outputs this signal of interest. Where to add some background. Using the typical 38KHz modulation, equates to a minimum resolution of 26.3uS per pulse's cycle. sherriff's library shows typically most bauds or bits are in the order of 10+ pulses. Which appear to meet your desired timings.

microtherion/Arduino-IRremote fork of shirriff's work improves the reception by replacing the timer interrupt polling of the pin with the use of PinChangeInterrupts. Which I have merged into my own mpflaga/Arduino-IRremote fork, that adds several other features.

So you could use any of the above libraries. Or create your own app that uses either of the below to capture edges.

polls on a Timer event (e.g. 50uS)
captures the micros() on a PinChangeInterrupt
uses Input Capture Interrupts to grab the exact time


How to get data from a sensor's FIRST IN FIRST OUT FIFO register (from two's complement) I want to get acceleration data from a ADXL355 sensor.

My code:

void readFIFO (){
long data[3];
byte data2 [9];

digitalWrite(chipSelectPin, LOW);
SPI.transfer( (FIFO<<1) | 1);
for (int i = 0 ; i < 9; i++){
    data2[i] = SPI.transfer(0x00);
}
digitalWrite(chipSelectPin, HIGH);

Serial.println("Byte data in hex and binary");
 for (int j = 0 ; j < 9 ; j++){
    Serial.print("element "+String(j) +": ");
     Serial.print(data2[j],HEX);
     Serial.print(" ");
     Serial.println(data2[j],BIN);
 }
 for (int z = 0 ; z < 3; z++){
    data[z] = ((data2[z*3]<<12) | (data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
 }
 Serial.println("concatenated values: ");
 for (int i = 0 ; i < 3 ; i++){
    Serial.println(data[i]);
 }
}

Sample output:

Byte data in hex and binary
element 0: F9 11111001
element 1: 1B 11011
element 2: 51 1010001
element 3: 0 0
element 4: FD 11111101
element 5: 90 10010000
element 6: C3 11000011
element 7: 2A 101010
element 8: 20 100000
concatenated values:
-28235
4057
12962

The values are two's complement. Are these the correct values? If not what am I doing wrong?

Since you've had no response to this I'll add my experiences with this chip. I'm not sure why you are reading the FIFO buffer. The chip provides three registers for each of the three axes. I simply read those in a loop. You can find my (still very crude) Python to read these at https://github.com/markrad/ADXL355. I hope it's some help to you.


Can you put Ardupilot on any flight controller? Some FC's say that they support cleanflight and have no mention of Ardupilot. Is this just because its what's recommended or because it's all that works?

There are pre-built binaries for many flight controllers.

http://firmware.ardupilot.org/ lists out the different ardupilot builds (arducopter, arduplane, etc.) and by clicking on them , you can see the different versions, then the different builds per version.

This document goes into more detail on the file structure they use for pre-built binaries.


Connecting multiple RS485 together I am trying to build communication across multiple Arduino using RS485. When i am trying to connect 3 Arudino nano together using breadboard my code doesn't reach slave where as if i just if i do direct connection between 2 RS485 without breadboard it works but i use breadboard for 2 it doesn't work. Am i missing any setup here?

Breadboard connection - A & B are connected to + & - of both RS485.

Working connection - A & B of first RS485 connected to A & B of 2nd RS485.

It is possible you have too many resistors on the RS485 bus. From the RS485 wikipedia page there is this quote:

  Ideally, the two ends of the cable will have a termination resistor
  connected across the two wires.

This may explain why you can use 2 of your RS485 interfaces but not 3.  Consider removing the resistors from the RS485 board in the middle if possible.


Can Arduino Leonardo use USB port and RX TX serial pins at the same time? Can I use the TX/RX on pins 0, 1 (to a serial slave device) while also having the USB port dedicated PC communication?

32u4 is multi-serial uC. USB connection works on default serial communication which can be used via Serial.print("somevalue"). On the other hand if you want to use RX/TX on pins 0, 1 which are actually RXD1 and TXD1. So, if you use Serial1.print("somevalue"). So the answer is a yes. You can use USB and RX/TX (hardware serial) at the same time.