texts: Controlling keyboard LEDs with USB Host Shield

texts:
I've got a USB keyboard connected to my Arduino Uno with a USB Host Shield. I'm reading keystrokes using this example from the USB Host Shield library.

I need to toggle the LEDs in the keyboard (that indicate the state of Caps Lock, Num Lock etc.)

This thread mentions using Usb.setReport(), but this method doesn't seem to exist any more: there's no such method in Usb.cpp in the library. There does seem to be a method called SetReport in the USBHID class, which looks like it takes the same arguments, which I'm trying to use.

What I'm currently doing:

void keyboard_setup(){
    static HIDBoot<USB_HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }
    delay(200);
    HidKeyboard.SetReportParser(0, &Prs);

    static USBHID usbhid(&Usb);
    uint8_t leds = 1;
#define KBD_ADDR 1
#define KBD_IF 0
    usbhid.SetReport( KBD_ADDR, 0, 1, KBD_IF, 0, &leds );
    delay(100);
    leds = 255;
    usbhid.SetReport( KBD_ADDR, 0, 1, KBD_IF, 0, &leds );
    delay(100);

Neither call to SetReport seems to work, and I'm not certain the values of KBD_ADDR or KBD_IF are correct (I'm using ones that I've seen in examples), or event that calling SetReport is right .

What am I doing wrong?


texts: I am using FastLED to drive 16 pixels on an addressable  WS2812B RGB LED strip. My application has extremely tight timing constraints. Specifically, I need to turn the LEDs on and off within less than 1 ms. I tried FastLED but it requires a minimum of 2.5 ms to execute the Show command, regardless of the number of LEDs attached. I analyzed another library and that one has the exact same limitation. In fact, I found a snippet of code that said roughly: "if this operation performs in less than 2500 us, then wait idly until the 2500 us have passed. Apparently this wait is necessary due to timing requirements of WS2812x strips. Does anyone have any advise about other addressable RGB LED strips or libraries that can be turned on and off within 1 ms?


texts: Problems Sending Signals to the Arduino-Uno via Keyboard

texts:
I have an Arduino Uno and a usb 2.0 shield in which I connected a keyboard to. I have all the necessary libraries installed but what I am trying to figure out is how to light an led when I press a specific key.
I am new to codding Arduino boards and I have done a lot of reading but I cant figure out my issue I feel like if I get this figured out I will be a lot better off in my future projects.
#include <hidboot.h>
#include <usbhub.h>
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

int SKEY = 8;

class KbdRptParser : public KeyboardReportParser
{
    void PrintKey(uint8_t mod, uint8_t key);

  protected:

    void OnKeyDown  (uint8_t mod, uint8_t key);
    void OnKeyUp    (uint8_t mod, uint8_t key);
    void OnKeyPressed            (uint8_t key);
};

void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
{
  MODIFIERKEYS mod;
  *((uint8_t*)&mod) = m;
  Serial.print((mod.bmLeftCtrl   == 1) ? "C" : " ");
  Serial.print((mod.bmLeftShift  == 1) ? "S" : " ");
  Serial.print((mod.bmLeftAlt    == 1) ? "A" : " ");
  Serial.print((mod.bmLeftGUI    == 1) ? "G" : " ");

  Serial.print(" >");
  PrintHex<uint8_t>(key, 0x80);
  Serial.print("< ");

  Serial.print((mod.bmRightCtrl   == 1) ? "C" : " ");
  Serial.print((mod.bmRightShift  == 1) ? "S" : " ");
  Serial.print((mod.bmRightAlt    == 1) ? "A" : " ");
  Serial.println((mod.bmRightGUI  == 1) ? "G" : " ");
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
  Serial.print("DN ");
  PrintKey(mod, key);
  uint8_t c = OemToAscii(mod, key);

}

void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
  Serial.print("UP ");
  PrintKey(mod, key);
}

void KbdRptParser::OnKeyPressed(uint8_t key)
{
  Serial.print("ASCII: ");
  Serial.println((char)key);
};

USB Usb;
HIDBoot<USB_HID_PROTOCOL_KEYBOARD>    HidKeyboard(&Usb);

KbdRptParser Prs;

void setup() {

 Serial.begin(9600);
#if !defined(__MIPSEL__)
  while (!Serial);
  Serial.println("Start");

  if (Usb.Init() == -1)
    Serial.println("OSC did not start.");

  delay( 1 );

  HidKeyboard.SetReportParser(0, &Prs);

}

void loop() {
 Usb.Task();
}

Anyways I know how to make if statements and how to activate pins on the Arduino but I cant figure it out in this keyboard library. For now I just made it print "TRUE" since there is not need to get complicated if I cant get the first step to work. Before I made that if statement the serial monitor would show the value assigned to the key and label it DN # and when I let up on the key it would say UP # but how can I translate that to sending a pulse to whatever pin when I push a key and stop sending a pulse when I let up on the key?
Also in my if statement that I made I know I need something before == sign but I tried multiple things and they did not work so I just left it blank and the reason I used the number 16 was because that was the value assigned to the S key in which I wanted to use to light an led. Anyways any help would be greatly appreciated!


texts: Arduino UNO serial send and receive issue

texts: I am trying to send and receive data from a PIC16F88 to an Arduino Uno. My problem is that the serial communication stops when the Arduino is not connected to the USB cable. For my application I need the Arduino to still perform its operations with a battery. I have tried both software and hardware serial. Is it possible for the Arduino to send/recieve data when not plugged into the USB cable?


texts: Giving the impression of a dying device - making a vibrating motor slow down and stop

texts:
I'm trying to make a gag gift for a friend. The effect I'm trying to imitate is of a device that starts up for a moment and then putters out like something is wrong.

So I need it to:
1. Vibrate a motor for a second or two.
2. Make the vibration sputter out.
3. Light up an LED behind an error message on a paper screen.

I have very little hands on experience with anything electronic, but I have some programming and I took enough physics to know what a capacitor, etc is.

My questions are whether an Arduino is a good and cost effective way to accomplish this and is there any beginner friendly advice anyone can give me to get this accomplish


texts: Combine bits from two ports into a single byte

texts:
I'm attempting to read the values of 8 pins at a time into a byte.

The obvious answer to this seems to be the Port registers, however with the way the Arduino is wired, I'd have to split my read across two registers.

In this case, I need a way to combine the lower 5 bits of PORTB with the upper 3 bits of PORTD into a single byte.

For example, this is the physical layout with the data lines I'm attempt to read/write to and their corresponding port assignments.

             SCSI
DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
|   |   |   |   |   |   |   |
PB4 PB3 PB2 PB1 PB0 PD7 PD6 PD5
            AVR

From what I can gather I need to use some shift operators to achieve this,
perhaps something like:

hi = PORTB & 3;
lo = PORTD >> 3;

But I'm unsure if that's correct and then how I would combine them.

Is it possible to write a macro to make getting and setting this byte easier?

Is there a good learning resource on bit manipulation like this?


texts: I want to make a device with a sensor I can attach to the places my dog likes to mark. When sensor becomes wet I want a buzzer to make a loud noise to scare the animal and notify me I need to encourage the dog to go outside. Any suggestions on what sensor to use.


texts: How can Arduino source code be tested automatically (continuous integration)?

texts: I'd like manage my Arduino source code (projects and libraries) under source control with continuous testing. How can I automatically compile the code with continuous integration tools, to make sure each version compiles cleanly? In the best case one should be able to configure builds for multiple processors, optionally run unit tests and check for maximum binary size.


texts:
I'm trying to write a library for (rather slow) communication with visible light and have recently tried to include the TimerOne library as a timer.
I want to send bits at 2kHz, so with a period of 500µs. I'm initializing the Timer1 with 500(µs) like this and then attach an interrupt to it to call my transmit function:

Timer1.initialize(500);
Timer1.attachInterrupt(transmitBit);

However, when I try to measure the period with a logic analyzer, it tells me that there is actually a period of 2,000µs. Could this be due to some overhead created by the library? Where else could the problem be?

If you need any other information just let me know and I'll try to provide it.

Thanks in advance for your feedback.

EDIT: I've just tried adding the period as a parameter to the attachInterrupt like so:

Timer1.attachInterrupt(transmitBit, 500);

And now I'm measuring a period of 30µs for whatever reason? Can anyone explain me what's going on?

EDIT: This is the rest of my (relevant) code:

Transmitter::Transmitter()
{
  [...]
  Timer1.initialize(500);
}

Transmitter* Transmitter::_instance;

void Transmitter::start() {
  _instance = this;
  Timer1.attachInterrupt(_transmitBit, 500);
  _active = true;
}

static void Transmitter::_transmitBit() {
  _instance->transmitBit();
}

void Transmitter::transmitBit() {
  if(_active) {
    //Preperation
    if(!_manHalf) { //only change the state when the manchester bit is completely transmitted.
      if(_busy) {
        //Serial.println("Transmitting!");
        /** if there is currently a transmission running
          * read the next bit from the frame
          */
        _state = *(_frame + _pos);
        if(_pos >= _frameSize) {
          _busy = false;
          _state = 0;
          _pos = 0;
        }
        _pos++;
      } else { //else transmit the idle pattern
        _state = 0;
      }
    }
    //Transmission
    if (!_manHalf) {
      digitalWrite(_pin, !_state);
    } else {
      digitalWrite(_pin, _state);
    }
    _manHalf = !_manHalf;
  } else {
    digitalWrite(_pin, HIGH);
  }
}


texts: Is it possible to package a sketch with dependent libraries for cross-platform compatibility?

texts:
I have a complex sketch that I spent many weeks working on, which I am backing up frequently because I'm afraid of losing any of my progress.

I'm wondering if it's common practice to make a self-contained package of the sketch and all its dependencies, so that it can be moved easily to another OS if necessary. My concern is that if my OS crashes and I have to reinstall everything or move to another OS, I might run into library and dependency errors, especially with the libraries that I altered/customized. I need my sketch to be able to compile as quickly as possible on whatever OS I end up using, since it's a home-automation sketch that controls dozens of things around me.

Is this a valid concern? And if so, what are some preferred ways to make a sketch become "self-contained", so that everything necessary is included? Is there some kind of a better version-control system for Arduino sketches that an amateur programmer might not be aware of?


texts: 'Keyboard' not found when trying to use Keyboard.write from the  library

texts:
I am trying to get a response from the arduino when I press a key, but when I try to upload the code it says that it could not find 'Keyboard' with 'Keyboard.write'. Here is my code. Ignore the bits with servo stuff, that is for the project later on. I am using the arduino mega 2560.

  #include <Servo.h>
  #include <Keyboard.h>

Servo myservo;
Servo myservo2;

int pos = 0;
int pos2 = 0;
String comdata = "";
int lastLength = 0;

void setup() {
myservo.attach(12);
myservo2.attach(11);
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}

void loop() {
if (Serial.available() > 0) {
 // read incoming serial data:
 char inChar = Serial.read();
 Keyboard.write(inChar + 1);
}

}


texts: PWM fans causing temp sensor erroneus values (interference?)

texts:
I am learning Arduino programming and my current project for real use is to connect 10-17 PC chassis PWM fans to be temperature controlled by the arduino.

So, I have connected the fans exactly as in the picture.
Taken from https://www.racedepartment.com/threads/easy-diy-wind-simulator-for-assetto-corsa.133999/

The temperature sensor is a TMP36 (included in the official Arduino beginner's kit). It is connected to +5V and GND on the Arduino Uno R3. Middle pin is the output and is connected to A0 on the Uno.

Temperature readings seem to work well up until the point the fans start spinning. When they do, the output pin on the TMP36 sensor outputs junk values. Such as 0V or 700mV and it fluctuates up and down if I try probing it with a multimeter. When fans some to a stop however, the output once again stabilizes to a fairly correct value.

I am no expert in electronics interference, but electric motors I suppose cause some electrical noise? I had hoped that PC Chassis fans would already have electric components inside the hub to prevent such though...
Currently I am trying to run 2 fans at the same time but I wish to use 10-17 later once this works.

The fans I am using are Arctic 92mm PWM Rev 02.

I have checked the datasheet (https://www.arduino.cc/en/uploads/Main/TemperatureSensor.pdf) for TMP36 (TO-92 package type) and tried adding a ceramic 0.1µF capacitor between +5V and GND and also add resistor of varying values to the output pin. I believe I got some stabilization out of it but not  enough. Especially when the fans start spinnig faster than 20% duty cycle on pwm it starts to flip out.

I have tried to disconnect power to fans to check if PWM signal may cause it too, but this is not the case as the TMP36 remain stable with PWM on but fans disconnected.

Can someone please help me with explaining what is probably going on and how I can mitigate the problem in a preferably easy way? Do I need to add diodes, capacitors, resistors? Where? Or should I change to a different temperature sensor (which)?

Thankful for help!


texts: Blink LED with different on off times just once with millis

texts:
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;
       }

      ```


texts: Reduce time between two consecutive SPI transfers on ESP32

texts:
I'm trying to drive an external DAC via SPI interface using ESP32 chip. But I cannot achieve the desired speed (>1M transfers/sec, each transfer consists of 16bits). The reason is not the SPI speed itself, which could be set as high as 40MHz, but the time delay between two consecutive SPI transfers.
A sample code is as follows:
#include <SPI.h>

void setup()
{
    Serial.begin(115200);
    SPI.begin();
    SPI.beginTransaction(SPISettings(40000000,MSBFIRST,SPI_MODE0));
}

void loop()
{
    unsigned long tstart=micros(),count=0;

    byte data[18]={0,1,2,1,3,1,0,1,2,1,3,1,0,1,2,1,3,1};

    while(micros()-tstart<1000000)
    {
        for(byte i=0;i<9;i++)
          SPI.transfer16(0b0101010110101010);
        count+=9;
    }

    Serial.println(count);
}

The output shows that ESP32 can do approximately 694,800 transfers/sec, still far away from my requirement of 1M transfers/sec. However, theoretically, using a 40M SPI bus, each transfer only takes 16/40M sec, which should enable a >2M transfers/sec speed, so the difference must originate from the time delay between two consecutive SPI transfers.
I know that these delays can possibly be canceled by transferring more data in a single transfer command. However, the interface of DAC requires me to pulse SYNC once (set it high and then low) before each SPI transfer, which is not possible if I use a single SPI transfer command.
I have searched for solutions online and found two related problems:
The one here suggests disabling all MUTEX commands in esp32-hal-spi.c/h. It seems reasonable, but I see no effects, probably because the compiler has already deleted those codes in optimization.
Another here suggests using RMT to replace SPI, but suffer from timing issues.
I think there is also room for improvement as I only need to output data, and I access SPI on a single thread, so the solution can be thread-unsafe.
So I'm here to ask, is there any way to accelerate the SPI transfers? Thanks a lot in advance!


texts:
The code below

// include the library code:
#include "LiquidCrystal.h"
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(2,4,5,6,7);

void setup()
{
// set up the LCD’s number of columns and rows:
lcd.begin(16,2);
// Print a message to the LCD.
lcd.print("hello");
}
void loop()
{
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}

Gives me the following error:

exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'


texts: Directly powering a single 32x16 RGB LED matrix (without external PSU)

texts:
All the guides I've found suggest to use an external PSU to power an RGB matrix like this.

However I know it is possible to blink the LEDs at high rates (eg. 2ms) and still give the impression to the eyes they are fully on. I've verified this myself on a small 4x4 matrix, but I am not sure if the same can be done with these bigger matrices.

In my case I could tolerate reduced brightness and color space, but I'd like to power the matrix with the Arduino's 5V pin directly.


texts:
To preface, I am very new to Arduino and I watched this video on YouTube.

It shows how you can build a motion controlled car with Arduino and I decided to make this for my school project.

One thing I am having difficulty with is connecting the MPU6050 to the Lilypad. In the video he doesn't really show much of it and just sticks it onto the board.

However, do I need to solder the MPU6050? Where do I solder the pins the underside or the top. Do I need to align the pins with that of the Lilypad?

Sorry if it's a stupid question I genuinely don't know.

The current condition of our lilypad:

What it's supposed to look like:

If you see the images, in addition to the yellow light of the MPU 6050 and the red light of the HC 05, the red light of the Lilypad is also supposed to light up like the second picture, however in ours, only the MPU 6050 and the HC 05 lights up and not the Lilypad.


texts: Displaying when Button has been pressed for LED and returning 1

texts:
I've just started using Arduino and I'm having trouble getting my code right.

Here is the task I need to do.

"Create a button read function
  Hint: the function header should be int checkbutton ( void )
in the loop function, add code such that if the button has been pressed (i.e. the checkbutton function
returns 1), a message is sent to the serial monitor with your username."

There are no errors in the code but nothing happens in the serial monitor when I press the LED button and it does not return 0 when i don't press the LED button.
Any sort of help would be appreciated!

Thanks!

int Button = 15; //LED and output are on the same pin

int last = 0;

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

int button() {
  pinMode(Button, INPUT);

  int current = digitalRead(Button);

  if (current and not last) {
    delay(5);

    pinMode(Button, OUTPUT);

    Serial.print("Hey");
    return 1;
  }

  else {
    pinMode(Button, OUTPUT);

    current == last;

    return 0;
  }
}

void loop() {
  if (button >=0)
  {
    button();
  }

  else
  {
    ;
  }
}


texts: Atmega 328p at 3.3v : Internal vs external oscillator

texts:
I am currently working on a pcb that uses smd atmega 328p (au).
I will be powering it through a lipo battery and a ldo regulator for 3.3v input. I am using the multiwii flight controller code.
I know that atmega runs at 8mhz at 3.3v and 16mhz at 5v without overclocking the chip.
The question is that should I use the internal 8mhz oscillator or external 8mhz?
I will definitely make the chip more accurate as given in some forums but still does this effects anything or not?


texts: How do I connect velostat to an arduino?

texts:
I have some velostat that I'd like to hook up to an Uno. At the risk of sounding dense...how do I do that?

Ultimately wanting to get readings of pressure from the velostat, just not sure how or what wires to connect where.


texts: EthernetClient not initializing properly

texts:
I am trying to make a connection with the EthernetClient, but it always fails with code 0. I decided to write a small code just to test if the client ever becomes ready, and as I suspected it does not.

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0x2A, 0x27, 0x55, 0x08, 0x1E, 0x6A};
IPAddress ip(172, 16, 48, 133);
EthernetClient client;

void setup() {
  Ethernet.init(10);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  while (!Serial) {;}

  for (auto link = Ethernet.linkStatus(); link != LinkON; link = Ethernet.linkStatus()) {;}
  Serial.println("Link ON");

  while(!client){
    Serial.println("Client not ready");
    delay(1000);
  }

  Serial.println("Client ready!");
}

void loop() {}

If I try to run the code above, it gets stuck at the "Client not ready" loop, and I can't figure it out what I'm missing for it to work.

Obs.: I have already configured a web server with success with my shield, so I'm guessing the problem is not with it.


texts: ESP8266 Bootloader Firmware (on the ESP8266)

texts: It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.  If that firmware is corrupted, the ESP8266 is dead.  I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.  Does anybody know how to do that?  Thank you.


texts: How do I connect 4 or more Arduinos to a single shared GSM Module?

texts:
Is it possible to connect 4 or more Arduinos to a single GSM Module.?
All the Arduinos need to send SMS at a specific time daily.
How do I make sure thet don't time collide with each other, other than sending sms at different times for each Arduino?.
I want the SMS to be queued up, and be sent one by one.


texts: How to find the peak value of analog signal?

texts: I have a question .. Please help me I don't know how Arduino can read the peak value of the sensor signal. The value I want is in the ADC value .. What I want is ... for 5 seconds there will be 1 average value from the highest peak value of the sensor, and the ADC value. I will use pin A0, but I don't know how to code the program that I want. Please help me What is the code?


texts: how to read arduino board info serial no programmatically

texts: well I am try to make an project with original arduino. but I want to make this project unique. if my codes are copied and loaded another arduino board, my app should not work. how can make unique app, are there any idea? on Arduino IDE Tools> Get Board İnfo> SN look unique id. but how can read it programmatically.


texts:
I have an Arduino Mega2560 and a Raspberry Pi hooked up through I2C. The Pi is acting as the master, while the Arduino is the slave. While sending data over I2C, the int message gets messed up and will either send the address or the data. Then I can't even receive any useful data from the Arduino.

So if I turn the receiving function off it sends the data just fine, but when I ask the Pi to start receiving data again it slows down the entire bus and data starts conflicting between the Pi and Arduino. Also it only happens with the Arduino. Every other device works flawlessly.

Here's what my code looks like on the Pi side. I'm using SMBus to send and receive bytes. I didn't bother to put up code for it because I don't have the source code for SMBus. I just trust that they work because my other I2C devices work without a hitch.

while True:
    #if alternating == true then get the imu if not then get the motor speed
    if alternating == True:
        try: #need the try because an error will stop the program completely
            ypr = IMU.getYPR()
            yaw = int(ypr['yaw'] * 180 / math.pi)
            savedYaw = yaw
        except:
            yaw = savedYaw
            #print "exception"
            pass
            #write yaw to arduino
            i2c.writeByte(yaw)
            alternating = False
        else:
            #start reading data from arduino
            #readArduino()
            alternating = True
            pass

Then on the Arduino side these are my onReceive and onRequest functions:

void readPI(int byteC) {
    if(Wire.available()) {
        reference = Wire.read();
    }
    pid1.getReference(reference);
    pid2.getReference(reference);
}

void sendPI() {
    int values[] = {(int)out, (int)outReversed  };
    Wire.write(values[count]);
    count++;
    if(count > 1) {
        count = 0;
    }
}

Is there something about the Arduino that I don't know? Maybe it's a timing issue? Is there a way to set up registers? I can either receive or send, but I can't do both, and Googling the problem only leads to an example of someone sending 1 - 9 over the Pi. I can't find examples of anyone actually doing something complicated with an Arduino and a Rasp Pi over I2C. Any and all help would be amazing!


texts: Using I2C to keep track of position of slaves

texts:
I am trying to flesh out my ideas for an electronics project and this question seems to be the main hangup. Is it possible, in the I2C protocol, to figure out the order in which the slaves are chained to the host? For example if I have 5 arduinos strung together by their serial and clock lines I want the master to be able to see that Arduino 1 is in position 1, Arduino 2 is in position 2... And so on. But if I switch Arduino 1 and 2 I want the master to know that Arduino 1 is in position 2 and Arduino 2 is in position 1.

I assume this isn't possible because all of the arduinos are connected to the same data and clock. So does anyone have any other protocols or algorithms in mind where I could do this. I was thinking I could have one Arduino talk to it's neighbors somehow and waterfall data down the line until it gets to it's destination. But I'm curious to see what y'all come up with.


texts:
I was scrolling through the ATmega328P datasheet when I came across a rather fascinating statement about the way in which the data part of the SPI interface is buffered. I can't seem to understand why the double input buffer is necessary. The following statement can be found on page 161 (Datasheet):

  The system is single buffered in the transmit direction and double buffered in the receive direction. This
  means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle
  is completed. When receiving data, however, a received character must be read from the SPI Data
  Register before the next character has been completely shifted in. Otherwise, the first byte is lost.

Can someone please briefly explain to me why the double input buffer is necessary?


texts:
I'm trying to connect my Arduino Uno to the Arduino IDE in Windows, but the only way it works is with a CH340 driver.
I am concerned about this as I can only find a download of it published by two Chinese companies- wch.cn or Jiangsu Qinheng Co., Ltd.- maybe they're both 1 company; even when Windows looked for a driver on the web that was the one it downloaded.
When I went to Device Manager to look for the driver in the official Arduino download zip, Windows said it couldn't find any drivers.
I am concerned about the security implications of the driver being Chinese and wonder if there are any other CH340 drivers (unless CH stands for China...)
Anyway thx for answering!!! :)


texts:
So I recently built a small IFTT powered button using an ESP8266 for my boys to play with. Tonight during an intense Thunderstorm, I kept getting alerts that it had been pressed. They weren't in the basement at all. Then I realized, giant crack of lightening === SMS message.

Now I don't think this has anything to do with the button mechanism itself, but the shoddy way I hooked it up, and stuffed it into an enclosure. I'm just curious - is this possible? Could some sort of static electricity from a few nearby lightening strikes do something that would send a 'high' signal to the GPIO Pin on my Espee? I had to use a pull up resistor, and I feel like there's probably a few bare-ish wires in there, but nothing touching, or even close enough to 'arc'. Am I crazy?


texts: A minor confusion in digitalWrite command

texts:
Will the Arduino IDE interpret digitalWrite(13,x), where x>0, as digitalWrite(13,HIGH)?
And will it interpret digitalWrite(13,x), where x<=0, as digitalWrite(13,LOW)?


texts: I2C: What is the difference between A4&A5 and SCL&SDA pins?

texts: On tutorials are most people using the A4&A5 pins with the Wire.h library. But i have an arduino with dedicated I²C pins. How can i use them?


texts: How to convert an hex string to an array of bytes?

texts:
How to convert the char array to Byte array? I tried every method but it doesn't work.

char CardNumber[8] = "B763AB23"; // Length is 8, basically it's in Hex
                                 // B7 63 AB 23

I need to convert it into Byte array to byte CardNumberByte[4];
So basically, it should be like :

CardNumberByte[0] = B7;
CardNumberByte[1] = 63;
CardNumberByte[2] = AB;
CardNumberByte[3] = 23;

I am unable to find any solution for that.


texts: NTP rollover-safe design with ESP8266 (Curiosity)

texts:
The Arduino NTP implementation is rather naive in some respects. It basically just grabs the time in seconds from the raw packet, and then converts it to Unix time via subtraction. How would it be possible to create an implementation that is safe from at least this next NTP rollover (due in 2036)? I'd rather not design something that might suddenly fail in strange ways in a decade or two when I have forgotten why it might do so (but it's not horribly important if it's not easily fixed).

If it can make it to 2100, I'd have larger problems (the RTC would crap itself), so just this rollover is fine.

The existing implementation (https://github.com/arduino-libraries/NTPClient/blob/master/NTPClient.cpp):

unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;

this->_currentEpoc = secsSince1900 - SEVENZYYEARS;


texts:
I'm trying to control an engraving machine with an Arduino Uno. I don't have so many knowledges in electricity so I'm trying something very simple. I think my program is OK but I have no idea how to plug the wires. I just want to mark non-stop
-Send a 250ms signal to the marking Input of the machine

-Marking.

-Waiting for output "Ready to mark" from the machine

-Wait 1 s

-Send a 250ms signal...ETC

These are the I/O of my machine:

and this is my program :

I need to send 20V to the inputs of my machine. How is it possible : I know that my company does it without external power supply and the arduino is just plugged on the I/O and the USB.

Can you help me ?

Thank you in advance.


texts: How do I change the Console colour of Arduino IDE?

texts:
Leading on from the question Can I change font Color and/or Type for IDE 1.5.6r2?, in 1.6.0, or 1.6.11 it does not seem to be possible to change console.color or console.error.color. To be precise, you can change the settings in the preferences.txt2 file, but they appear to be ignored when the IDE is restarted. Have these become hard coded?  I see from the preference.txt example file that

# Some colors have been hardcoded into the source in app/ in order to ensure
# consistency with the images distributed and stored with the application.
# They have been commented out below so that users who install an old
# version of the software will not get incorrect colors left-over from this
# config file.

However, the settings to which I refer are not commented out, and so would led me to believe that they can be changed. Orange text on black is just horrific to read.

For example:

console.error.color=#FFF000
console.color=#FFCCCC

but I still get white/orange(red?) text for the output and error messages respectively.

I am making the edits while the Arduino IDE is not running.

1 In 1.6.3 the ignored console.color etc. lines appear to have been removed from the preferences.txt file.

2 C:\Users\username\AppData\Roaming\Arduino15\preferences.txt


texts: Which Arduino is compatible for atmega164pa

texts: I am working on a project using 5 pins of ADC, 5 pins for PWM, and LCD. I need to use Atmega164pa. I would like to know how I can transfer it to Arduino. Is there any Arduino compatible with this chip?


texts:
I'm using an Arduino Due board with an optocoupler 4N25 to simulate a button pressed.
I have to open and close a circuit that drive an actuator. In that circuit, when connected, with the tester I'm measuring 6V.

I connect the anode to the pin 12 and the cathode in series with a 150-ohm resistor to ground, and Collector and Emitter from optocopupler to the circuit (and a normal Blink example with the pin 12).

When optocoupler is fired on and off respectively with a tester I measure 0V and 1.7V in the arduino part, and 4V and 6V.

This is not enough and the actuator is always run. I'd like to read 0-6V instad of 4V-6V. Does this depends on how much current goes to the anode/cathode of the optocoupler? Do I have to change the resistor in the arduino part? Any kind of advice? What can I do?

I don't want to use relay because I have read that in respect to a relay they are faster, smaller, longer-lived and quieter.


texts:
simulate this circuit – Schematic created using CircuitLab

Wiring is based on the scheme presented below -

(Reference: https://electronics.stackexchange.com/a/174580)

I am using Arduino Mega 2560, HX711 and four load cells to build a weighing scale but having a hard time calibrate the unit. I have tried different libraries and calibration schemes but none of them seem to help. I have found that the raw values corresponding to any given weight (including zero load) are not consistent. Firstly, the readings do not settle even after 10 minutes, and even if I take an average, the next time I put the same weight, I get an entirely different reading making the last average useless. I am seeing errors of the order of +/- 30 lbs when I put a known weight.

I first thought that maybe my load cells are the root cause but when hooked them up directly to Arduino and read the voltage across the bridge, I read stable constant values. Verified the voltage readings with a Voltmeter. (Yes, their resolution is not as good as HX711 but at least they are stable and consistent). I get the voltage reading close to my hand calculations.

Next, I tried testing the HX711 in different ways. In one test, I created a full-bridge using resistors other than load cells, forced the bridge out of balance but cannot read anything other than 16777215. Next, I wanted to see if the board is reacting to any voltage at all, so, I removed the bridge and did not connect anything to E+ and E- pins but supplied known voltages from a DC power supply (from 0 to 4.5V) to the A+ and A- (GND) pins. Now, it is reading only 8388607, no matter what voltage I supply. If I supply +5V or +3.3V from Arduino to the A+ and A- (GND) pins instead of DC Power supply, it then only reads 16777215.

I don't know how to interpret this behavior. How can I resolve the issue and bring the error down? Thanks for your help.

I have included the schematic below. All four Load Cells (LCs) are 3-wired (White, Black & Red). Resistance between W & B wires is around 1980 ohms while that between R & W or R & B is around 990 ohms. SO I connected the four LCs in the manner shown in the schematic. Wire colors have been labelled.

Code:

Code is pretty straightforward as I am simply reading raw values from the HX711 using the following HX711 library - github.com/queuetue/Q2-HX711-Arduino-Library.git

#include <Q2HX711.h>

const byte hx711_data_pin = 4;
const byte hx711_clock_pin = 8;

Q2HX711 hx711(hx711_data_pin, hx711_clock_pin);

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

void loop()
{
  Serial.println(hx711.read());
  delay(500);
}


texts:
I'm trying to upload an simple blink sketch to my Arduino Nano, which not used for a while.
As I remember, I uploaded an sketch to control RF module, at the last time I used. Now, when I connect my Arduino Nano, I 'm getting error message every second, from my serial monitor saying the the RF communication cant start, because I have disconnected all connections to the RF module.
It seems the Nano is working, and the Nano driver is working properly. I tried resetting manually, and uploading many times with random timings. But up to now, the sketch not uploaded, and waiting. When I press reset button while uploading, Arduino shows me the error it cant communicate.
I think the Arduino IDE not getting enough time to upload from serial, because it's busy all the time.
Is there any way to wipe out the existing sketch from Nano? or any working solution to upload my new empty sketch or simple blink sample? It's a big help if anyone can shed me some light to make my Nano work again.


texts: How accurate the an attiny timer function

texts:
I have an AT-Tiny (trinket) and I want to trigger LED on for 30 seconds every 24 hours. I'm using the timer library as follows

timer.setInterval(86400000, toggleit());

void toggleit()
{
  turnLightOn();
  delay(6000);
  turnLightOff();
}

How accurate will this be, if it's off by a few minutes each day that's fine, but will this drift over time? Also does it make a difference if I'm running it in 8 or 16 bit mode?


texts: Will this code for braking of dc motor using sensor work?

texts:
#define trigPin 13
#define echoPin 14
#define e1 10  // Enable Pin for motor 1
#define t1 8   // Control pin 1 for motor 1
#define t2 9   // Control pin 2 for motor 1
#define led 3
#define led2 5
#define buzzer 4

float duration,distance;
#include<SoftwareSerial.h>

void setup() {
 Serial.begin(9600);
 pinMode(trigPin,OUTPUT);
 pinMode(echoPin,INPUT);
 pinMode(e1, OUTPUT);
 pinMode(t1, OUTPUT);
 pinMode(t2, OUTPUT);

}

void loop() {
  digitalWrite(e1, HIGH);
  digitalWrite(t1, HIGH);
  digitalWrite(t2, LOW);

  digitalWrite(trigPin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin,LOW);

duration=pulseIn(echoPin,HIGH);
distance=(duration/2)*0.0343;
Serial.print("Distance= ");
if(distance>=400||distance<=2)
{
  Serial.println("out of range");
}
else if(distance<=100&&distance<=50)

{
  digitalWrite(led,HIGH);
  delay(1000);
  analogWrite(e1,157);
  digitalWrite(t1,HIGH);
  digitalWrite(t2,LOW);
  delay(500);
}
else if(distance<=50&&distance>=25)
{
  digitalWrite(buzzer,HIGH);
  delay(100);
  analogWrite(e1,56);
  digitalWrite(t1,HIGH);
  digitalWrite(t2,LOW);
}
else if(distance<=25&&distance>=10)
{
  digitalWrite(led2,HIGH);
  delay(100);
  analogWrite(e1,0);

}
else if(distance<=390&&distance>=100)
{  digitalWrite(e1, HIGH);
  digitalWrite(t1, HIGH);
  digitalWrite(t2, LOW);

}

delay(500);
}


texts: What terminologies and concepts describe the codes that follow a format of Text1.Text2()?

texts:
I'm just really curious because some codes really follow a format like this. Examples include serial.begin(), serial.println() and when I used servomotors the left part was the name of the servomotor, which I declared. I want to know what concept does the code with a format of Text1.Text2() refer to? What do you call Text1 and Text2? Are there official or commonly used terminologies for the concepts and parts such as "variable", "statement", "code"?
To add to my understanding, it appears that Text1 refers to an object and that Text2 has the concept of "function" where it performs something related to the object. Though I would think that another terminology would be possessed by Text2 other than function to distinguish it from a function since it is required to be written in the format I mentioned, which next to the object with a period separating them and no spaces at all.


texts: Arduino + UltraSensor - Serial Monitor outputs garbage

texts:
I am trying to connect an HC-SR04 to an Arduino Uno. For some reason when I run this code on the serial monitor it outputs wingdings in a straight line.

ýòøÿüÿøÿüòý÷ÿ÷ýÿÿúýÿýúÿòý÷ûòûòû÷ýÿøÿøÿÿ÷øÿüÿýÿþòøòÿÿøûüÿøÿÿòÿ÷ûòûòý÷ûòûòûöû÷ÿûû÷øÿÿ÷øÿüÿýÿüÿûöþÿý÷ûòûòûòûöûûûûûò

No breaks. Sometimes when I hit "Tools/Fix Encoding and Reload" it outputs

Ping: 0 cm
Ping: 0 cm
Ping: 0 cm

followed by more wingdings.

I've looked up some similar problems and it was usually fixed by changing baud to a lower value, 9600. I've done this and I still have problems.

Would you be able to help me out? I'd very much appreciate it.

const int trigpin = 9;
const int echopin = 10;
long duration;
int distance;

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

void loop() {
  pinMode(trigpin, OUTPUT);
  pinMode(echopin, INPUT);
  digitalWrite(trigpin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(trigpin,LOW);
  duration = pulseIn(echopin,HIGH);
  distance = duration *0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
}

Updated Solution

After testing out Joel's code to check the sensor was in order, I found some new sample code which worked to display the distance in inches of a HC SR04 sensor.

  // set up variables

  int trigpin = 13; // Trig Pin is connected to Arduino pin 13
  int echopin = 11; // Echo Pin is connected to Arduino pin 11

 // now we need variables which we will be measuring

 float pingtime; // Time for ping to travel to target and return
 float targetdistance; // Distance from sensor to target
 float speedofsound = 776.5; // speed of sound in miles per hour at 77 F

void setup() {
Serial.begin(9600); // Turn on serial port
pinMode(trigpin, OUTPUT); // Sensor trig pin is output
pinMode(echopin, INPUT); // input is reading from echopin

 }

void loop() {
digitalWrite(trigpin, LOW);// set trigger pin low
delayMicroseconds(2000); // pause to let signal settle
digitalWrite(trigpin, HIGH); // set trigger pin high
delayMicroseconds(15); // pause in high state, make sure sensor reads
digitalWrite(trigpin, LOW); // bring trigpin back low

   pingtime = pulseIn(echopin, HIGH);

// sensor will be sending HIGH pulse, measure pingtime at echopin
// ping time is in microseconds

  pingtime = pingtime / 1000000.;

// converts pingtime to seconds because speed of sound is miles per hour

  pingtime = pingtime / 3600.;
  // converts pingtime to hours
  // add a period to make float to avoid int mistakes

  targetdistance = speedofsound * pingtime;
  // calculates distance in miles traveled by ping

  targetdistance = targetdistance / 2;
  // accounts for roundtrip of ping to target

  targetdistance = targetdistance * 63360.;
  // convert target distance to inches
  // 63360 inches in a mile

Serial.print("The distance to the target is:");
Serial.print(targetdistance);
Serial.println("inches");
delay(1000);

 }


texts:
A quick question about microcontroller digital level on I/O pins. I have a photo interrupter which is powered at 3.3V which is interfaced to Arduino UNO running at 5V.

For microcontroller to detect high or low level is determined by signal higher than 5V*(2/3) = 3.33V is high and signal lower than 5V*(1/3) is low. What I don't understand is that arduino is able to detect the level change from the photo interrupter. Doesn't the supply on pins have to be greater than (2/3) or Vcc in order for it to detect logic high? The circuit works and I am able to count pulses from the interrupter but I want to know why that works considering the photo interrupt only gets about 3.23V.

Please clarify


texts:
I am having a temporary lapse of judgement, or not understanding how the power method works, but when I put 10 to the power of a number, it is that value -1.  So:

10*10 = 100

Then I would assume, 10^2 = 100

So if I had a variable i, that was equal to 2, and I asked arduino for 10 to the power of i, I would expect it to do 10^2, and then give me 100, but instead I get 99.  What am I missing?

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

void loop() {
for (int i =0; i<5; i++){
   int power = i;
   Serial.print(power);
   Serial.print(":");

   int multiplier = pow(10,power);
   Serial.println(multiplier);

  }

}


texts: 4-20 milliamp to volts to pressure maths

texts:
I am measuring pressure in bars from OsiSense™ XMLP pressure sensor (4-20 milliamp) on a arduino uno.  When the machine im measuring pressure on is switched off the reading is 0v as expected.
When the machine is on (the sensor is on) the reading is 1v as expected.
When the machine is on and hydraulics are active the voltage fluctuates as expected.

The problem I have is I don't know the maths to translate the voltage to bar pressure.

From a previus question i've asked from 0v to 5v the equation is:

// This is for the DEFAULT 5V analog reference.
// v = the voltage at the pin in Volts.
// p = the pressure in bar.
// Note that 'bar' is the pressure relative to the
// normal atmospheric pressure at that moment.
float v = (float) analogRead(A0) / 1024.0 * 5.0;
float p = v / 5.0 * 100.0;"

Is it just a matter of changing the equation to take into account the 1v when the sensor has power and then dividing by 4 instead of 5:

RawVoltage = (float) analogRead(A0) - 1;
float v = RawVoltage / 1024.0 * 4.0;
float p = v / 5.0 * 100.0;"


texts: How to load scal factor external to the code?

texts:
We know that, we need calibration factors (scale factors) to read current sensor data (ACS758) to arduino. I am also using voltage reader using voltage divider circuit for my project. I need to build 5 such boards and need to change calibration factor in main program everytime due to tolerance of componenets. Currently for one of my board reference_factor is 0.81 and this will change due to resistor tolerance for other boards.

Because of this issue I need to maintain 5 different codes for 5 different boards. These sensor values controls on and off of certain relays. (Not shown in the code).

can I load this referrence_factor externally through text file or as any other medium so that I need not change the code everytime.? I am using arduino Nano.

int reference_Factor = 0.81;

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

void loop() {
  // read the raw data coming in on analog pin 0:
  int lightLevel = analogRead(A0);
  // Convert the raw data value (0 - 1023) to voltage (0.0V - 5.0V):
  float voltage = lightLevel * reference_factor;
  // write the voltage value to the serial monitor:
  Serial.println(voltage);
}


texts:
I recently purchased a W5100 based ethernet shield for my arduino Uno, and looks like this. I had been following the guide here, and connected the pins accordingly - 5V to 5V, GND to GND, MOSI to 11, MOSO to 12, SCK to 13, and SS to ten.

I booted up a default sketch (webServer, under Ethernet), and plugged in and ethernet cable. - PWR, LINK, SPD,and FDX all lit up, with Rx blinking for first 10 or so seconds. I then go to the IP specified on the arduino sketch, and nada. Also, my router doesn't show the shield under the attached devices.

Therefore, I figure it's a problem with my connections. Can anyone help me? Googling has only brought my lots of info about shields, and little info on these modules.


texts: Why is the constrain function used after the map function?

texts:
I am reading some sample code and they use this method of mapping data from IR sensors:

  sensor1 = analogRead(0);
  adj_1 = map(sensor1, s1_min, s1_max, 0, 255);
  adj_1 = constrain(adj_1, 0, 255);

What is the point of using constrain here if adj_1 is already getting a value 0-255 from the map function?


texts: Problem on color mixing lamp on Proteus Arduino starter kit

texts:
I set the circuit and couldn't illuminate, where is the problem?

Fritzing: https://fritzing.org/media/fritzing-repo/projects/c/color-mixing-lamp/images/Arduino%20Lamp%20Project.png


texts: Powering an Arduino Mini Pro using a CR2032 battery as a remote control

texts:
I'm looking into making my own remote control using an Arduino Mini Pro and some RF transceivers. The receiving end won't be a problem, but the remote will. I want to make it as small as possible and consume as little energy as possible.

Is it possible to turn on the Arduino Mini Pro at the push of a button, while also using that same button to trigger a piece of code? That way I can cut the power when it's not being pressed.

I will make sure to code it, so I have to hold the button down for 1-1.5 seconds, so it has time to "boot up" and send the RF signal, but should power off immediately when I let go of the button.

What kind of power should I expect from a single CR2032 battery? I have a couple of NRF24L01 RF transceivers laying around together with an Arduino Mini Pro.

If we assume this, while looking at this sheet:

NRF24L01: 10 mA per second (low-ball)
ATmega328P: 5 mA per second (low-ball)
CR2032: 0.19 mA @ 2V = 2100+ hours

Even if we just say 600 hours and it takes 2 seconds to turn something on, I should be able to run it  600H*60M*60S = 2.160.000 seconds = 1.080.000 times. If my calculation isn't completely wrong, it means I could literally turn it on a million times in the worst case scenario.

I hope that calculation is wrong, because that seems crazy.

EDIT: I could desolder the LED and regular as well, if that won't damage it too much. Just to consume power. I've read I can basically run it for free then.


texts: What is the best serial communication method between an Arduino and a spectral sensor?

texts:
I have an Adafruit AS7262 visible spectral sensor. I want to receive the data of the sensor with an Arduino.
The sensor has two serial communication options: UART(asynchronous) or I2C(synchronous). I want to know which method is more suitable for the sensor to communicate with the Arduino microcontroller. I was thinking that UART is more suitable, because the sensor has his own master clock, in other words if I choose I2C then the Arduino needs to work as the "slave" and I dont think that is very suitable, because the Arduino has its own master clock also. For this reason I think that asynchronous method is more reliable, but I am not sure about this.


texts: "Serial" does not name a type -> How to solve this problem?

texts:
I'm trying my best to solve this problem but it didn't changed

The red line was drawn on the last Serial.println */

int cds = A0;
int led = 12;
int trig1 = 2;      // Left Trig
int trig2 = 3;      // Right Trig
int trig3 = 4;      // Front Trig
int trig4 = 5;      // Upside Trig
int echo1 = 6;      // Left Echo
int echo2 = 7;      // Right Echo
int echo3 = 8;      // Front Echo
int echo4 = 9;      // Upside Echo
int vib1 = 10;      // Left vib
int vib2 = 11;      // Right vib

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

        pinMode(trig1, OUTPUT);
        pinMode(trig2, OUTPUT);
        pinMode(trig3, OUTPUT);
        pinMode(trig4, OUTPUT);
        pinMode(echo1, INPUT);
        pinMode(echo2, INPUT);
        pinMode(echo3, INPUT);
        pinMode(echo4, INPUT);
        pinMode(vib1, OUTPUT);
        pinMode(vib2, OUTPUT);

        Serial.begin(9600);
}

void loop(){
  long duration1, value1;
  long duration2, value2;
  long duration3, value3;
  long duration4, value4;

  // Ultra Sonic Sensor Part1
  digitalWrite(trig1,LOW);                           // Trigger Output
  delayMicroseconds(2);
  digitalWrite(trig1,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig1,LOW);
  duration1 = pulseIn(echo1,HIGH);                   // Read Pulse Duration
  value1 = microsecondsToCentimeters(duration1);     // Count Distance
  delay(10);

  // Ultra Sonic Sensor Part2
  digitalWrite(trig2,LOW);
  delayMicroseconds(2);
  digitalWrite(trig2,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig2,LOW);
  duration2 = pulseIn(echo2,HIGH);
  value2 = microsecondsToCentimeters(duration2);
  delay(10);

  // Ultra Sonic Sensor Part3
  digitalWrite(trig3,LOW);
  delayMicroseconds(2);
  digitalWrite(trig3,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig3,LOW);
  duration3 = pulseIn(echo3,HIGH);
  value3 = microsecondsToCentimeters(duration3);
  delay(10);

  // Ultra Sonic Sensor Part4
  digitalWrite(trig4,LOW);
  delayMicroseconds(2);
  digitalWrite(trig4,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig4,LOW);
  duration4 = pulseIn(echo4,HIGH);
  value4 =  microsecondsToCentimeters(duration4);
  delay(10);

  //Commend Part (Vibration motor)

  // Print Out Value
  Serial.print(" dist1 =");
  Serial.print(value1);
  Serial.print("(cm)");
  Serial.print(" dist2 =");
  Serial.print(value2);
  Serial.print("(cm)");
  Serial.print(" dist3 =");
  Serial.print(value3);
  Serial.print("(cm)");
  Serial.print(" dist4 =");
  Serial.print(value4);
  Serial.print("(cm)");
  delay(10);
  //

  // Initialize PIN Mode
  digitalWrite(vib1,HIGH);
  digitalWrite(vib2,HIGH);

  // 진동모터1,2,3
  if (  value4<60  or  value3<60)
  digitalWrite(vib1,LOW);
  digitalWrite(vib2,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);
  digitalWrite(vib2,HIGH);

  if (0< value1 && value1<60)
  digitalWrite(vib1,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);

  if (0< value2 && value2<60)
  digitalWrite(vib1,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);
}

// Function of Count Distance

long microsecondsToCentimeters(long microseconds)
{
  return microseconds/29/2;
}

        int cdsValue = analogRead(cds);

        Serial.print("cds =  ");
        Serial.println(cdsValue);

        if (cdsValue < 38 ) {
                digitalWrite(led, HIGH);
        } else {
                digitalWrite(led, LOW);
        }


texts:
I'm new to the Arduino and I asked some questions around here and they were really helpful so I'm hoping I will get help once more

#define maxLen 800

volatile  unsigned int irBuffer[maxLen]; //stores timings - volatile because changed by ISR
volatile unsigned int x = 0; //Pointer thru irBuffer - volatile because changed by ISR

void setup() {
  Serial.begin(9600); //change BAUD rate as required
  attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//set up ISR for receiving IR signal
}

void loop() {

  Serial.println(F("Press the button on the remote now - once only"));
  delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
    Serial.println();
    Serial.print(F("Raw: (")); //dump raw header format - for library
    Serial.print((x - 1));
    Serial.print(F(") "));
    detachInterrupt(0);//stop interrupts & capture until finshed here
    for (int i = 1; i < x; i++) { //now dump the times
      if (!(i & 0x1)) Serial.print(F(" "));
      Serial.print(irBuffer[i] - irBuffer[i - 1]);
      Serial.print(F(", "));
    }
    x = 0;
    Serial.println();
    Serial.println();
    attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for receiving IR signal
  }

}

void rxIR_Interrupt_Handler() {
  if (x > maxLen) return; //ignore if irBuffer is already full
  irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

}

I would like to modify the code above to write to an SD file instead of printing it on the serial port. I've tried to use myFile.write or myFile.print but it won't work. Maybe I am just not that aware of how the SD functions work. Any tips?
This is a function to capture IR signals. I require them for a Arduino remote.
The modified code:

//you may increase this value on Arduinos with greater than 2k SRAM
#define maxLen 800

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

File myFile;

volatile  unsigned int irBuffer[maxLen]; //stores timings - volatile because changed by ISR
volatile unsigned int x = 0; //Pointer thru irBuffer - volatile because changed by ISR

void setup() {
  Serial.begin(9600); //change BAUD rate as required
  attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//set up ISR for receiving IR signal
}

void loop() {
  // put your main code here, to run repeatedly:

  Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    while (1);
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  Serial.println(F("Press the button on the remote now - once only"));
  delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
    Serial.println();
    myFile.print(F("Raw: (")); //dump raw header format - for library
    myFile.print((x - 1));
    myFile.print(F(") "));
    detachInterrupt(0);//stop interrupts & capture until finshed here
    for (int i = 1; i < x; i++) { //now dump the times
      if (!(i & 0x1)) myFile.write(F(" "));
      myFile.print(irBuffer[i] - irBuffer[i - 1]);
      myFile.print(F(", "));
    }
    x = 0;
    Serial.println();
    Serial.println();
    attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for receiving IR signal
  }

}

void rxIR_Interrupt_Handler() {
  if (x > maxLen) return; //ignore if irBuffer is already full
  irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

}


texts:
I am looking to use an Arduino to monitor an incoming audio source (mobile radio/HAM/Walkie Talkie) for a transmission and send this stream through the car audio system speakers. Speaking back on the radio isn't important, but might explore using the car system for that as well.
My car provides the built in ability to listen to FM radio with my phone paired through bluetooth. When a call comes in on my phone, the car system detects and mutes the FM radio to play a ringtone from my phone over the car speakers. It also displays caller info, but I don't care about that for the radio audio. My car also has wired only Apple CarPlay. I would like to be able to plug my iPhone in through the cable for music streaming, and then connect my mobile radio through bluetooth to have the short messages mute the music and play the radio audio similar to the phone ring.
I am seasoned with Arduino but pretty new to bluetooth. Research so far looks like the ring and other actions happen through AT type of commands within the Headset Profile. Page 23 of the PDF below shows a RING command, but no ability to set the specific 'ringtone' if you will. Page 34 of the PDF suggests there is a way to set these ringtones or even an audio notification. Are these capable of relaying a live stream such as a mobile radio source?
Reference PDF: https://www.silabs.com/documents/public/application-notes/AN992.pdf
Is this something possible with a bluetooth module on Arduino?
The alternative scenario I can fall back on would be a Bluetooth middle man that can accept multiple audio signals (hopefully with bluetooth as an option), and then mute the primary source to play the secondary. I prefer above so I can use the CarPlay functions.


texts: Arduino Uno to Arduino Uno Word.doc file transfer

texts:
I have written a 2 sets of code for the transmitter and receiver section. I am trying to send a word document file from 1 arduino uno to the next arduino uno through serial TX and RX. The file is initially loaded into a micro sd card module at the transmitter section. I would like to transfer that file to the receiver section's sd card module. I am able to receive an empty word document at the receiver section. There is no information in the document. I would like some help with this. I will attach the transmitter and receiver code below.

Transmitter code:

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

File fileIn;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
   while (!Serial){
    ; //  wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(!SD.exists("student.txt")){
    fileIn = SD.open("student.txt", FILE_WRITE);
    fileIn.println(F("abc.txt"));
  }
  fileIn = SD.open("student.txt", FILE_READ);

  while(fileIn.available()){
    Serial.write(fileIn);
  }
  delay(1000);
  fileIn.close();
}

void loop() {
  // put your main code here, to run repeatedly:

}

Receiver code:

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

File fileOut;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial){
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(SD.exists("student2.txt")){
    SD.remove("student2.txt");
  }
  fileOut = SD.open("student2.txt", FILE_WRITE);

  while(fileOut.available()){
    Serial.write(fileOut);
  }
  delay(1000);
  fileOut.close();
  Serial.println("It worked!");
}

void loop() {
  // put your main code here, to run repeatedly:

}


texts: Can't power mg2639 cellular shield with battery

texts:
I have a SparkFun MG2639 cellular shield attached to an Arduino Uno R3.  I have had both the cell modem and the GPS unit working when the shield is powered from the Uno.  I followed the instructions on SparkFun's site to switch the shield to be powered by battery (cut SJ2, short SJ3) and connected a fully charged Li-ion battery.  I measure over 4.1 volts at the battery connection pads on the shield but the power LED isn't on and the shield isn't responding.  It looks as though it's not getting any power.  I also powered it from my bench supply with 5V and it shows no current draw.

Did I miss something in the conversion instructions?


texts: Using an external interrupt alongside serial

texts:
I want to read data from an accelerometer sensor, which pushes its data to the Arduino via an external interrupt. I then want the Arduino to relay this data to a host computer via the serial connection.

Will the external interrupt interfere with the serial connection? If the Arduino's in the middle of transmitting via serial, and the accelerometer triggers the interrupt, won't that potentially break the serial connection?


texts: OBOE: Need help understanding, possible type conversion issue

texts:
I have an algorithm that its main purpose is decoding, converting, or what have you a string of uppercase letters (A-Z) into a number. This is almost like converting a base 26 number into base 10, however I believe that a base 26 number encoded would actually include numbers, I am working strictly with uppercase letters, I digress.

I have an implantation working in C++11, in fact most of the controller algorithm was a direct copy, with a slight change to the indexOf method.

The C++11 version works as I expect it to. So initially I thought the new indexOf method was incorrect, but after a simple test, it is working as expected. I have narrowed down the problem to a line in the convertTo10 where I am calling the pow function.

As you can see from the Serial.println()'s in the convertTo10 method, the output is printing exactly what we expect, 0 & 26.

However, the output of this function is 25. WHAT?

I have read the docs on the pow method from the Arduino lib, and it takes in two floats and returns a double. Even if the issue was a type conversion issue, converting a double to an int truncates the number, it does not round it. Well, this is from working with C++.

Any help with this issue would be much appreciated.

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <inttypes.h>

#include <Arduino.h>
#include <avr/pgmspace.h>
#include <Wire.h>

const char _values[26] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z'
};

const int _val_len = 26;

int indexOf(char needle);
int convertTo10(String value, int len);

String x = "BA";
int len = 2;

void loop() {
  Serial.print(x);
  Serial.print("=> ");
  Serial.println(convertTo10(x, 2));
  delay(50000);
}

int convertTo10(String value, int len) {
    int lastIndex = len - 1;
    double output = 0;
    int pos = 0;
    Serial.println();
    for (int i = lastIndex; i >= 0; i--) {
        int r = indexOf(value[i]);

        output += (r * pow((_val_len, pos));
        Serial.print("     output => ");
        Serial.println( output );
        pos++;
    }
    return output;
}

int indexOf(char needle) {

    int first = 0;
    int last = _val_len - 1;
    int mid;

  do {
    mid = (first + last) / 2;

    if (_values[mid] == needle)
      return mid;
    if (_values[mid] > needle)
      last = mid - 1;
    else
      first = mid + 1;
  } while (first <= last);

  return -1;
}

For Reference, Here what it is outputting:

BA =>
     output => 0.00
     output => 26.00
25


texts: Arduino Nano memory issue. SD card and LCD screen together

texts:
When i am uploading my code to arduino nano, i am getting message about high dynamic memory usage (87%):

Sketch uses 17,628 bytes (57%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,751 bytes (85%) of dynamic memory, leaving 297 bytes for local variables. Maximum is 2,048 bytes.
Low memory available, stability problems may occur.

But despite this, its uploading to my arduino nano and everything works fine without action method's code. How to use code (code to work with LCD) wich is located in action() method. If i use hidden code, im getting message error opening test.txt (not enough memory). But if code which is controls LCD screen is annotated then SD card works fine.

If i use this code, i'm getting problem with SD card. But i can still use LCD and SD on same arduino board separately without any problems, but if i try to combine it, im getting some problems with SD card reading.

void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

All code:

#include <Wire.h>
#include <Adafruit_SSD1306.h>

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

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)

int count_iterations = 0;

#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

File myFile;

void setup() {

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
  //// SD END
}

void loop() {
  sensorValue = analogRead(analogInPin);
  if (sensorValue < 1000) {
    action();
  }
}

void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}


texts: Why can I measure two pins simultaneously?

texts:
I would like to do an action if both buttons on my arduino pro micro are depressed simultaneously. I'm getting some strange results:

// Buttons
Bounce button0 = Bounce();
Bounce button1 = Bounce();

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ;
  }

  pinMode(2, INPUT_PULLUP);
  button0.attach(2);
  button1.interval(1);

  pinMode(3, INPUT_PULLUP);
  button1.attach(3);
  button1.interval(1);

  Serial.println("Setup Complete");
}

void loop() {
  button0.update();
  button1.update();

  if (button0.fell()){
     Serial.println("button0 fell");
  } else if (button0.rose()) {
    Serial.println("button0 rose");
  }

  if (button1.fell()){
     Serial.println("button1 fell");
  } else if (button1.rose()) {
    Serial.println("button1 rose");
  }

  if (button0.fell() & button1.fell()){
    Serial.println("buttons fell");
  } else if (button0.rose() && button1.rose()) {
    Serial.println("buttons rose");
  }
}

Here is the output to the Serial console:

Setup Complete
button0 fell
button1 fell
button0 rose
button1 rose

Why isn't this branch being executed? button0.fell() & button1.fell() For the life of me I cannot figure this out. Thank you!

EDIT

This doesn't work either, which is crazy:

void loop() {
  button0.update();
  button1.update();

  if (button0.fell()) {
    if (button1.fell()) {
      Serial.println("buttons fell");
    }
  }

  if (button0.rose()) {
    if (button1.rose()) {
      Serial.println("buttons rose");
    }
  }
}

EDIT

Thank you for the answers! Unless the person was to push both buttons in the exact same iteration of the loop, my code would never work. Here is what I ended up using:

if ((button0.fell() && !button1.read()) || (button1.fell() && !button0.read())) {


texts: How to check whether my arduino-mega ADC is sampling correctly?

texts:
I have a code which samples the given input signals with sampling rate 256hz. I plotted the graph of FFT and was able to see the peaks at the expected frequencies.But I would like to know whether my ADC is sampling correctly or not?Is there a way to do it?`

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

const unsigned long READ_PERIOD = 3906;  // 3906 us: 256 Hz
void loop() {
    static unsigned long lastRead;
    if (micros() - lastRead >= READ_PERIOD) {
        lastRead += READ_PERIOD;
        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A3);
        int val_a2 = analogRead(A5);
        int val_a3 = analogRead(A7);
       Serial.print(val_a0);
       Serial.print("  ");
       Serial.print(val_a1);
       Serial.print("  ");
      Serial.print(val_a2);
      Serial.print("  ");
        Serial.println(val_a3);
    }
}


texts: Multiple timers with different frequencies

texts:
I have to use multiple timers (for example, to blink different LEDs) with different frequency (for example, 7.3 Hz). Cannot you tell me, what is the preferred way to implement it?

Just now I use one simple TimerOne timer and just check what LEDs should be inverted and what are not, but I don't think it's a good idea.

#include <TimerOne.h>

#define PIN_RED 52
#define PIN_GREEN 50
#define PIN_BLUE 48
#define PIN_YELLOW 46

#define N_LEDS 4

float freqs[N_LEDS] = {1, 2, 3, 4};
int pins[N_LEDS] = {PIN_RED, PIN_GREEN, PIN_BLUE, PIN_YELLOW};

long int usec_to_invert[N_LEDS];
long int full_usec_to_invert[N_LEDS];

boolean led_states[N_LEDS];

int who_is_next()
{
  int next_to_invert = 0;
  for(int i = 0; i < N_LEDS; i++)
  {
    if(usec_to_invert[i] < usec_to_invert[next_to_invert])
    {
      next_to_invert = i;
    }
  }
  return next_to_invert;
}

void process_timer()
{
  int to_invert_now = who_is_next(); // Смотрим, кого надо инвертировать на этот раз
  long int time_past = usec_to_invert[to_invert_now];

  for(int i = 0; i < N_LEDS; i++)
  {
    usec_to_invert[i] -= time_past;
  }
  led_states[to_invert_now] = !led_states[to_invert_now];
  digitalWrite(pins[to_invert_now], led_states[to_invert_now]);
  usec_to_invert[to_invert_now] = full_usec_to_invert[to_invert_now];

  int next_to_invert = who_is_next();
  long int time_to_pass = usec_to_invert[next_to_invert];
  if(time_to_pass <= 200)
  {  // The interrupt processor should finish work
    Timer1.setPeriod(200);
  }
  else
  {
    Timer1.setPeriod(time_to_pass);
  }
}

void setup()
{
  Serial.begin(115200);
  for(int i = 0; i < N_LEDS; i++)
  {
    pinMode(pins[i], OUTPUT);
    led_states[i] = false;
    full_usec_to_invert[i] = (long int)(1000000. / freqs[i] / 2.);
    usec_to_invert[i] = full_usec_to_invert[i];
  }

  int next_to_invert = who_is_next();
  Timer1.initialize(usec_to_invert[next_to_invert]);
  Timer1.attachInterrupt(process_timer);
}

void loop()
{
   delay(1000);
}


texts: Unable to connect esp8266 12 module with arduino uno

texts:
Here is what I am doing

Arduino(UNO)--------Esp8266
3.3 v -- vcc
TX      -- RX
RX      -- TX
3.3 v  -- EN(ch_pd)
GND     -- GND

there is no blinking of LED on Esp8266, sometimes the LED is on and sometimes it is not. And when I send "AT" command using Serial of Arduino IDE, only RX light of Arduino blinks, TX is not blinking and there is no response of that command. I am having 3.3 voltage on my Vcc pin of Esp8266 but the voltage on the TX and RX pins of Esp8266 is 5 volts, I know that i can reduce this to 3.3 voltage by using a voltage regulator but my question is why there is no blinking on the module even when i have supplied the proper 3.3 voltage and GND?
What's the difference between the blinking and a still LED on Esp8266?
I have tried every tutorial on internet. No help at all. Right now I am so exhausted that I want to quit.If you can help in solving the problem, I would be very thankful to you sir.


texts:
I wrote a code that controls a stepper motor using the AccelStepper library. When it receives a serial signal from Visual Basic that contains a coordinate value, the Arduino will control the stepper motor by this value. The code works very well but it runs 1 second after receiving the value over the serial port. I want the code to run faster. Here is the code:

#include <AccelStepper.h>
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper(1, 9, 8);

int pos = 0;

void setup()
{
  Serial.begin(115200);
  stepper.setMaxSpeed(90);
  stepper.setAcceleration(90);
}

void loop()
{
  if (Serial.available()) {
    int steps = Serial.parseInt();
    stepper.moveTo(steps);

    if (stepper.distanceToGo() == 0) {
      stepper.moveTo(stepper.currentPosition());
      stepper.setSpeed(100);
    }
  }
  stepper.run();
}


texts: Connecting Arduino Mega + SIM800L to a car battery

texts:
I need to make a car tracker powered from a car battery. The problem is the SIM800L needs to be powered with 3.8v to 4.2v, and at 2A preferably. I want to connect the car battery to my Mega first then the Mega powers the SIM800L.

So:

Car battery > Mega > SIM800L

What do I need to achieve this?

This is the SIM800L model:


texts: How to prevent ATTiny program from running after I flash it with Arduino?

texts:
I am making a simple voltage regulator. The whole idea is to just use ADC to read voltage on output side and based on the result, adjust PWM power. I am using PWM on physical pin 5. That's the same pin as the one connected to Arduino pin 10 on this image below:

This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen. How can I flash the program safely? Can I do something to prevent it from starting?


texts: Storing and sequencing output value (arduino)

texts:
I am new to Arduino programming, after days and nights trying to use array,for loop and googling a lot of article, I still unable to find the way how to store each weighing output value from int Sampling() to be executed by the respective servo in sequence order.
If you have any clue to share and help me, I'll be very happy. Thank You very much.
Below is my base code.
#include <HX711.h>
///////////////////////////////////////////////////////////////////////
#define calibration_factor -251
#define LOADCELL_DOUT_PIN 7   // data
#define LOADCELL_SCK_PIN 8    // sck
////////////////////////////////////////////////////////////////////////
HX711 scale;
////////////////////////////////////////////////////////////////////////
int servo1 = 12;
int servo2 = 13;
int proxiPin1 = 2;
int proxiPin2 = 3;
////////////////////////////////////////////////////////////////////////
int toggleState = 0;
int proxiState1 = 1;
int proxiState2 = 1;
////////////////////////////////////////////////////////////////////////
int weight;
int weightFinal;
////////////////////////////////////////////////////////////////////////
void setup()
{
  Serial.begin(9600);
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale(calibration_factor);
  scale.tare();

  pinMode(servo1, OUTPUT); // simulating servo1
  pinMode(servo2, OUTPUT); // simulating servo2
  pinMode(proxiPin1, INPUT_PULLUP); // proximity
  pinMode(proxiPin2, INPUT_PULLUP); // proximity

}
/////////////////////////////////////////////////////////////////////////
void loop()
{
  Serial.print(Sampling());
  Serial.print(" gram");
  Serial.println();
  ///////////////////////////////////////////////////////////////////////
  if ( weightFinal == 10 )
  {
    toggleState = true;
    servo10gr();
  }

  if ( weightFinal == 20 )
  {
    toggleState = true;
    servo20gr();
  }
}
////////////////////////////////////////////////////////////////////////
int Sampling()
{
  int weight = scale.get_units();

  if (weight >= 10  && weight< 20)
  {
    weightFinal = 10;
  }

  else if (weight >= 20  && weight < 30)
  {
    weightFinal = 20;
  }

  return weight;
}
/////////////////////////////////////////////////////////////////////////
int servo10gr()
{
  proxiState1 = digitalRead(proxiPin1);
  if ( proxiState1 == 0 && toggleState == true )
  {
    digitalWrite(servo1, HIGH);  //Simulating servo signal Pin//
    delay(500);
    digitalWrite(servo1, LOW);

    toggleState = false;
    weightFinal=0;
  }
}
/////////////////////////////////////////////////////////////////////////
int servo20gr()
{
  proxiState2 = digitalRead(proxiPin2);
  if ( proxiState2 == 0 && toggleState == true )
  {
    digitalWrite(servo2, HIGH);    //Simulating servo signal Pin//
    delay(500);
    digitalWrite(servo2, LOW);

    toggleState = false;
    weightFinal=0;
  }
}


texts: How do I calibrate an ESC after connecting it to an Arduino?

texts:
I'm trying to connect an Arduino to an Electronic Speed Control and failing horribly. I'll explain what I've done so far, and then I'll explain the problem.

Before we get there, here's the list of parts I'm using:

Arduino Uno (genuine)
6V to 8.4V rated 18300 RPM 350 g-cm brushed motor.
Traxxas XL-5 brushed motor ESC. 1600 Hz is the highest PWM signal it accepts, if I'm not wrong.
Venom 4200mAh NiMH 8.4V battery pack (will replace soon with a 7.2V).

So I first connected the ESC to the motor. The connection is this bullet lead connection (the connection seems intact), and then the ESC to the Arduino. I connected the white wire to pin 9 and the black wire to ground. If I'm not wrong, this is the standard servo motor setup. I then plugged the Arduino into my computer, which has an intact USB port. Lastly, I connected the battery pack to the ESC.

Now I've tried to upload some basic code to try and calibrate my ESC, but it just plain our refuses to work. Under no circumstances will the motor run.
The code I'm using just sends the signal sent by the signal monitor.

I'm a complete noob to Arduino, so I don't know what could be wrong. The program I have in mind needs to be able to run while not connected to the computer, activate when a push-button switch is activated, run the motor for a certain distance (which involves an encoder, right?), and then stop.

Any pointers or things I could be doing wrong?

int value = 0;
Servo myservo;
void setup() {
    firstESC.attach(9);    // attached to pin 9
    Serial.begin(9600);
}
void loop() {
    myservo.writeMicroseconds(value);
    if(Serial.available())
        value = Serial.parseInt();    // Parse an Integer from Serial
}

and the one here:

#include <Servo.h>
#define MAX_SIGNAL 2000
#define MIN_SIGNAL 700
#define MOTOR_PIN 9
Servo motor;
void setup() {
    Serial.begin(9600);
    Serial.println("Program begin...");
    Serial.println("This program will calibrate the ESC.");

    motor.attach(MOTOR_PIN);

    Serial.println("Now writing maximum output.");
    Serial.println("Turn on power source, then wait 2 seconds and press any key.");

    motor.writeMicroseconds(MAX_SIGNAL);

    // Wait for input
    while (!Serial.available());
    Serial.read();

    // Send min output
    Serial.println("Sending minimum output");
    motor.writeMicroseconds(MIN_SIGNAL);
}
void loop() {
}

^shamelessly copied from the internet


texts:
I have 8 LED's connected to a shift register on my arduino uno r3. I am trying to write a Python3 script that will prompt a user to select one of the LED's and then prompt to toggle on or off.

Should be pretty basic but I cant seem to get this working.

I have already botched my code trying to get this running:

the jist of my python script is

import serial
import os
import time

os.system('clear')

ser = serial.Serial('/dev/cu.usbmodem1431', 9600)

while True:
    led = input("Which LED do you wish to operate? (press x to quit): ")

    if led >= '0' and led <= '7':
        print("Operating LED # %s" % led)
        ser.write(str.encode(led)) # sends the choice of led to arduino'
        on_or_off = input("Do you want to turn it on or off (press 0 for off and 1 for on): ")

        if on_or_off == '0':
            #send command to arduino to turn off the selected LED
            print("Command sent to arduino to turn OFF LED %s" % led)
            ser.write(str.encode(on_or_off))
        elif on_or_off == '1':
            #send command to arduino to turn on the selected LED
            print("Command sent to arduino to turn ON LED %s" % led)
            ser.write(str.encode(on_or_off))
        else:
            print("Please enter 0 or 1 to operate the LED. ")

    elif led == 'x':
        ser.close()
        break
    else:
        continue

For some reason Arduino is only dealing with the first input...

HEre is my loop code on the arduino

void loop() {
  if(Serial.available() > 0){
    led = Serial.read(); // from python script the led to operate
    led = led - '0';
    if(led >= '0' && led <= '7'){
      if(Serial.available() > 0){
        ledState = Serial.read(); // expects the led state next
        ledState = ledState - '0';
        if(ledState == '0'){
          shiftWrite(led,LOW);
        }else if(ledState == '1'){
          shiftWrite(led,HIGH);
        }
      }
    }
  }
}

shiftWrite is a function I wrote because there are 8 LEDS hooked to a shiftRegister

update:

I tried the state machine suggestion and it didnt work...

  void loop() {
  while(Serial.available()){
    led = Serial.read();
    led = led - '0';
    if(led>= 0 && led <= 7){
      state = 1; //We've received the LED # go to state 1
      Serial.println(led);
      Serial.println(state);
      Serial.println(ledState);
      continue;
    }
    if(state == 1){
      ledState = Serial.read();
      ledState = ledState - '0';
      if(ledState == '0'){
        shiftWrite(led,LOW);
      }else if(ledState == '1'){
        shiftWrite(led,HIGH);
      }
      state = 0; //Ended the operation return to state 0
    }
  }
}

With the serial monitor in the arduino IDE open (not running the python script) I tried this input: 4,1

This is my output on the serial monitor:

4
1
0
1
1
0

Any ideas? Basically the same problem as before...I actually thought the state machine idea would work...


texts:
I am trying to read from a ps2 barcode scanner (Datalogic gryphon D).
The Arduino is powered by the USB. The circuit is shown below

The pinout of the ps2 is

I have used the fritzing pin assignments when making the diagram.

I am using the code from here

#include <PS2Keyboard.h>

const int DataPin = 8;
const int IRQpin =  5;

PS2Keyboard keyboard;

void setup() {
  delay(1000);
  keyboard.begin(DataPin, IRQpin);
  Serial.begin(9600);
  Serial.println("Keyboard Test:");
}

void loop() {
  if (keyboard.available()) {

    // read the next key
    char c = keyboard.read();
    Serial.print(c);
  }
}

The scanner scans and indicates that the scan was successful. The Arduino code shows "Keyboard Test:", but none of the scans show anything. What am I doing wrong?


texts: Press on pressure sensor once, turn on LED for 6 seconds

texts: I am working on a project where I would like to press on a pressure sensor (0-1024) once and turn on the LED and turn off by itself after 6 seconds. I am quite new to arduino and I can't seem to understand how to code this with using a pressure sensor as a switch rather than an actual switch. Any ideas?


texts: ESP8266 NodeMCU first WS2812 LED lights up green

texts:
I'm trying to power some WS2812 LEDs from my ESP8266 ESP-12E NodeMCU board (circuit here). I'm simply trying to use the NeoPixel Strandtest which works perfectly on my Arduino UNO with the same LED strip, but when I change the #define pin 6 to #define pin D4 (or 12 as GPIO) only the first LED lights up and it's green. I did throw in a 470 ohm resistor between data and DIN, but that didn't do anything different.

When I use one of the other pins, nothing seems to light up, even if I disconnect all pins and hit reset. Here is my wiring:

Don't mind the actual 3v -> 5v. It works fine with 3v. I have also tried powering it off externally. I have tried all other pins from D0 to D7 (I saw many people say "STAY AWAY FROM PIN D8"). Could my ESP8266 be dead on arrival?


texts: Can I use micros() to analyze TX23 anemometer signal?

texts:
I'm very new to Arduino, and I'm trying to read data from a LaCrosse TX23 V02(X) anemometer. It's supposed to behave like this https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/, but it's not...

I don't have an oscilloscope, so I made this code, using micros() to try to trace the output from the TX23:

void loop() {
  collectData();
}

int collectData(void){
   if (bitLength < 0){
      bitLength = 1200;// length of bit is equal to approx 1230 micro seconds;
   }
  // init sequence
  pinMode(dataPin, OUTPUT);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  Serial.print("Send HIGH\n");
  digitalWrite(dataPin, HIGH);
  delay(100);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  delay(500);

  Serial.print("Begin input mode\n");
  pinMode(dataPin, INPUT);

  int state = 0;
  int oldstate = 0;
  unsigned long oldmicros = micros();
  for (int i = 1; i<5250 ; i++) {
    state = (digitalRead(dataPin) == LOW)? 0:1;
    if (i%10 != 0) {
      Serial.print("-");
    } else {
      Serial.print("+");
    }

    delayMicroseconds(10);
    if (state != oldstate) {
      oldstate = state;
      i = 1;
      Serial.print(oldstate);
      Serial.print(" @");
      Serial.print(micros() - oldmicros);
      oldmicros = micros();
      Serial.print("\n");
    }
  }
  Serial.print(state);
  Serial.println(micros()-oldmicros);
}

Does it have a chance to provide a quite accurate monitoring of the TX23 output? (eg is using micros() or delayMicroseconds(10) accurate ?)


texts: Will a magnetometer give distorted values if there is a magnet near?

texts: I am not entirely sure how a magnetometer works in IMU units, so I was wondering how a magnet near the sensor affects readings?


texts:
I'm new to the Arduino world and am working on a sketch to run a servo up and down with a spdt switch.
 My code is :

include #include<Servo.h>
int pos = 0;

Servo myservo;
void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  myservo.attach(9);
}
void loop() {
  if (digitalRead(2) == HIGH && pos < 180) {
    pos++;
    servo.write(pos);
    delay(15);
  }
  if (digitalRead(3) == HIGH && pos > 0) {
    pos--;
    servo.write(pos);
    delay(15);
  }
}

When I compile I get the "unexpected primary-expression before ';' token" error with exit status 1.

What am I doing wrong???


texts: Code uploads successfully on esp8266-01 but doesn't run

texts:
I am using esp8266-01 board. It was working fine few days ago, the codes uploaded and ran successfully. But now that I upload code to it, it gets uploaded successfully but it doesn't work.

I am using arduino nano to program it. It is connected as:
esp-01       arduino nano
tx-------------tx
rx-------------rx
vcc------------3v3
ch_pd----------3v3
gpio0----------gnd
gnd------------gnd

the code is basic blink code:

void setup(){
   pinMode(2, OUTPUT);
   }
void loop(){
   digitalWrite(2, HIGH);
   delay(500);
   digitalWrite(2, LOW);
   delay(500);
   }

This code gets uploaded successfully (According to IDE atleast) but it doesn't run. LED connected to gpio2 is always on. I also tried gpio0 and gpio1 but no luck.

I have already spend days trying to fix this. Please Help.


texts:
Am interfacing HX711 with arduino to measure the load of something. However, in my project, I need to continuously monitor the load.

I get fairly accurate values most of the time however, at times I suddenly get a junk value. For example, I call the weight function every 3 seconds and I have placed a 10kg weight, this is what I get. 17.25 is the concern.

10.04, 10.03, 17.25, 10.04, 10.03, 10.03

Am using HX711 library and my process function is a simple call as shown below.

float Processweight()
{
  Serial.print(scale.get_units(40), 2);

  scale.power_down();              // put the ADC in sleep mode
  delay(500);
  scale.power_up();
}

is there something that am missing? What could cause the wrong values?


texts: SoftwareSerial read until available is empty only works with delay

texts:
I originally was only going to make my program work on an ESP until I needed it on an Arduino UNO (because  I suspect my ESP is broken).
I had to add SoftwareSerial support but because I didn't originally intend to, the strings I send from my app have no terminators on them. I thought this would be fine because I could do something like:
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}

All that is doing is creating a string out of the recieved characters. It then checks if there is nothing left to read, and stuff has already been read (ie data has a length), then print the data.
What I expect the output to be is (if the input string in 03:255,255,255):
03:255,255,255

What I actually get is:
0
3
:
2
5
5
,
//and so on

That is becuase, for some reason, even though ble.available() should return a number not 0 at the if statement, it returns 0 and therefore the statement will always become true.
The only way I've fixed this is by adding in a little delay at the end of the loop. Whether that be:
delay(10)

or even this, in the while loop:
Serial.println(ble.available()) //This introduces enough delay somehow

Without having to modify my app, can I pull this off without using a delay? With delays it seems hacky especially because for all I know, for older or newer devices this delay could be too high or too low.


texts: how to write program for line follower with adafruit motor shield

texts: i have analog sensor with Ada-fruit motor shield how to write the program to control motors, please tell me the program to run the motor


texts: How can I set up outputs without using digitalWrite?

texts:
Consider the following:

#define IN1 9
#define IN2 10

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

void LeftMotor(Direction direction) {
  digitalWrite(IN1, direction == Forward ? LOW : HIGH);
  digitalWrite(IN2, direction == Forward ? HIGH : LOW);
}

How can I modify the LeftMotor method to achieve the same result without using digitalWrite?


texts: Receiving two values over serial port using servos

texts:
So I have a java program that picks up the mouses x and y coords on the display and I would like to send those to my arduino and then move my two servos to those locations (I have two servos ontop of each other, one for x and one for y).

The java (processing) code i have is below

void draw(){  //same as loop in arduino
  background(52, 152, 219); // background color of window (r, g, b) or (0 to 255)
  //lets give title to our window
  fill(0, 255, 0);               //text color (r, g, b)
  textFont(font);
  text("Ripple Effect Maker", 80, 30);  // ("text", x coordinate, y coordinat)
  ellipse(mouseX, mouseY, 33, 33);
  int x = mouseX;
  int y = mouseY;
  port.write(x+":"+y);
  println(x+":"+y);
  //println("y="+y);
  delay(100);
}

I don't have much arduino code because I can't seem to find a way to split the data into two seperate variables and then move the servos to their corresponding variables.

Thanks for the help!


texts: Possible to live-control an Arduino microcontroller from any Linux IoT board?

texts:
I'm working on a home project that centers around a non-Arduino Ubuntu IoT board but I'd like to add an ATmega32U4 chip for USB HID.

I'm thinking about using an Arduino Micro.

The signals to the Micro would have to come from my other board (maybe a Python script), but I haven't found instructions on how to send instructions in real-time from Other Board to Arduino Micro so they go straight through the Micro to the computer it's attached to.

How can one do this?


texts: how do i convert to assembly code (AVR assembly) from arduino

texts:
i have code in the Arduino ide for a temperature sensor that shows the temperature on three 7 segment displays, it shows the temperature to one decimal point. using an arduino uno. I am struggling to convert the below code to assembly. can someone please help?

#include <SevSeg.h>
#include "SevSeg.h" // Included the library for the 7 segment display
SevSeg sevseg;  // Created an object
const int sensor_pin = A0; // initialized A0 for LM35 sensor
float tempc;  //variable to store temperature in degree Celsius
float sensor_out;  // variable to store the output
unsigned long interval = 1000; // the time we need to wait
unsigned long previousMillis = 0; // millis() returns an unsigned long.
void setup() {
 pinMode(sensor_pin, INPUT);  // Declared the sensor pin as Input
 byte numDigits = 3;      it to 3.
 byte digitPins[] = {10, 11, 12};
 segment displays
 byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};
 pins of displays
 bool resistorsOnSegments = true;
 bool updateWithDelaysIn = true;
 byte hardwareConfig = COMMON_CATHODE;   // Type of display we are using
 sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
 sevseg.setBrightness(100);
 }
 void loop() {
  sensor_out = analogRead(sensor_pin);
  tempc = (sensor_out * 500) / 1024;
  tempc = tempc - 32;
 tempc = tempc * 5;
 tempc = tempc / 9;
 delay_function();
 sevseg.refreshDisplay();
}
void delay_function() {
unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
sevseg.setNumber(tempc, 1);   // Sets temperature on display
previousMillis = millis();
}
}


texts:
When i run a test code in Newping library for ultrasonic sensor SR04 then in works properly but when i run the actual code for obstacle avoiding robot then it shows 0 cm everytime. This means that wiring is correct but there is something wrong in my code below

#include <NewPing.h>
#include <AFMotor.h> //import your motor shield library

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_64KHZ); // set up motors.
AF_DCMotor motor2(2, MOTOR12_8KHZ);

int distance;

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

void loop() {
  delay(50);
  distance = sonar.ping_cm(); // start the scan
  delay(20);
  if (distance < 2) {
   Serial.println("Close Obstacle detected!" );
   Serial.println("Obstacle Details:");
   Serial.print("Distance From Robot is " );
   Serial.print(distance);
   Serial.print( " CM!");// print out the distance in centimeters.
   delay(10);
   Serial.println (" The obstacle is declared a threat due to close distance. ");
   Serial.println (" Turning !");
   motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
   motor2.run(BACKWARD);

}
  else {
   Serial.println("No obstacle detected. going forward");
   delay(15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
   motor2.run(FORWARD);
  }
}

Test code for sensor which worked:-

#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Tell me whats wrong here

Motor Shield used below
Wiring of sensor is connected to Arduino below the shield