texts: PWM Input Pins Never Receive a Value from Working Receiver?

texts:
I have a very simple sketch that's supposed to intercept the signal from an RC receiver and print the pulse duration from that channel.

Sketch

int PwmPin = 9;
unsigned long duration;

void setup() {
  pinMode(PwmPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  duration = pulseIn(PwmPin, HIGH);
  Serial.println(duration);
}

Output

0
0
0
...

My setup is the normal one that would occur without an Arduino, and only the battery is connected through the ESC to provide power to the receiver. The Arduino is connected via USB because I'm just trying to read values.

I have been trying to plug between the receiver's data pin to the Arduino's PWM pin and read the pulses from the rudder channel. (I have previously tested the channel with a servo and know that it works correctly). However, no signal (0) is being printed to the serial monitor. I have difficulty understanding why.

I checked the documentation for pulseIn(), and it seems simple enough. I tested PWM pins D3, D5, D10... none of them works. I don't understand where the problem is at this point. Update: I am now connecting from the receiver's negative pin to one of the Arduino's GNDs.

This is a simplistic scenario, so I don't see what's going wrong (my programming experience is good, but my experience with Arduino is near nil).

The goal of this experiment is to program lights to change according to throttle input, and asymmetric thrust through two motors for a boat. I know that pulseIn isn't the best function to use, but for the moment I just want to do some quick development before getting into the weeds.

Update:
I am attempting to follow this video, except that connecting the Arduino to the receiver didn't work, possibly because the ESC's BEC sends some sort of power signal that arms the receiver. (The receiver's LEDs usually make a visual signal, but they just turn on without a signal when connected through the Arduino).

According to the manual on page 6 and page 8, "receivers have an operational voltage range of 3.5 to 9 volts", with an ideal voltage being above 4.8V (because servos tend to brownout sooner). This should fall within Arduino range at 5V.


texts:
I am planning to build a little game and I would need to move a small magnet inside a rectangular area. Ideally I would be able to control movement arbitrarily e.g. using a joystick.
I am trying to find a way of doing this, something like an actuator, I guess, but allowing movement in 2D.
Any suggestions on which parts to use?

Edit : in brief, what I'm trying to do is this. I have a piece of plywood, underneath which I want to put a magnet. The magnet will be moveable using a joystick (everything controlled through an Arduino) and will be used to move a magnetised figurine on the other side of the plywood. I guess in term of precision of movement I am not looking for extreme precision, having something accurate to 2-3mm would be absolutely fine. Haven't really thought of speed... But not looking for extreme high speeds.


texts: Arduino is not recognized by any computer

texts:
I have an Arduino Uno R3 and when I plug it into any computer, the computer doesn't recognize the Arduino. I checked up and the LEDs are working fine and when I open the device manager it doesn't show any Unkown Device.

What it could be? Could the ATMega be dead? I tried on two Windows 7 and one Linux machines, none recognized the Arduino.


texts: Arduino serial controlled tone generator only working with single digit ints?

texts:
I'm writing a small program for my arduino which allows me to send two int values over serial to be interpreted. The first is a frequency Hz value and the second is a a length milsec value.

The code works, and plays the correct tone for the correct amount of millis, but only for single digit integers. If a double or more digit integer is sent then the arduino loops through the code several times and plays the wrong tone.

Here is my code:

const byte LED = 13; /* LED Pin */
const byte SPK = 12; /* Speaker Pin */
const int BAUD_RATE = 19200; /* Baud Rate of Input */

void setup(){
  pinMode(LED, OUTPUT);
  pinMode(SPK, OUTPUT);
  Serial.begin(BAUD_RATE);
  Serial.setTimeout(0);
  tone(SPK, 1000);
  delay(200);
  noTone(SPK);
  Serial.println("System ready for data");
}

void loop(){
  Serial.println("tone");
  while(Serial.available() == false){
    delay(0);
  }
  int toneToPlay = Serial.parseInt();
  Serial.println("delay");
  while(Serial.available() == false){
    delay(0);
  }
  int delayValue = Serial.parseInt();

  tone(SPK, toneToPlay);
  delay(delayValue);
  noTone(SPK);
}

Expected result is the ability to enter any tone and delay and the arduino plays it then asks for another tone and delay.

Any help is much appreciated.

EDIT: Here is my new code. It does what I want, the only issue is there is a pause after I type the tone value before it asks for the delay value, and a pause after the delay value before it plays the tone. I can't have this delay as data will eventually be sent by a piece of software to the arduino. How can I fix this delay? New code:

const byte LED = 13; /* LED Pin */
const byte SPK = 12; /* Speaker Pin */
const int BAUD_RATE = 19200; /* Baud Rate of Input */

void setup(){
  pinMode(LED, OUTPUT);
  pinMode(SPK, OUTPUT);
  Serial.begin(BAUD_RATE);
  tone(SPK, 1000);
  delay(200);
  noTone(SPK);
  Serial.println("System ready for data");
}

void loop(){
  Serial.println("tone");
  while(Serial.available() == false){
    delay(0);
  }
  int toneToPlay = Serial.readString().toInt();
  Serial.println("delay");
  while(Serial.available() == false){
    delay(0);
  }
  int delayValue = Serial.readString().toInt();

  tone(SPK, toneToPlay);
  delay(delayValue);
  noTone(SPK);
}


texts: How to extract the binary from STM32 MCU

texts: I have an already programmed STM32MCU. But I don't have the source code. I understand it is difficult to get the source code from the IC. I have heard some people can get the binary file from the IC which I can flash to another Arduino. Any guide or material will be helpful. I tried my luck with google. but didn't find any good resources on this matter.


texts: Leonardo (32u4): Timer0 problems with CTC mode

texts:
I want to use timer 0 to generate a rectangular signal on OC0A (D11) without the use of Arduino specific functions (that use timers for themselves). When I toggle D11 manually using a loop, I hear a sound in the connected piezo, but with my sample code, I don't hear something:

#define ALARM_PIN 11

void setup() {
  digitalWrite(ALARM_PIN, LOW);
  pinMode(ALARM_PIN, OUTPUT);
  noInterrupts();

  OCR0A = 60;
  // Toggle OC0A on compare match
  TCCR0A = (0 << COM0A1)
         | (1 << COM0A0)
  // CTC mode
         | (1 << WGM01)
         | (0 << WGM00);
  // prescaler = 256
  TCCR0B = (0 << WGM02)
         | (1 << CS02);
}

void loop() {
}

Any idea, what could be wrong?

Update

I've played with it a little bit more:

#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 250);
}

This causes my LED to light very dim, so the timer is running up to 255. But as soon as I set TCCR0A, nothing is lighting up:

#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  OCR0A = 60;
  TCCR0A = (1 << WGM01);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 0);
}


texts:
I have an arduino Uno with a motor shield attached I would like to drive 2 12 volt dc motors. Can I just attach a 12 volt power supply to the arduino Uno?

I ask because if I can attach a 12 volt power supply to the uno, I would like to also try and drive some leds from the Uno as well. I remember that the VIN jumper needs to be connected if connecting a power supply through the Arduino uno. There is also a pin labeled VIN.

If I can connect a 12 volt power supply to the arduino uno, can I power the leds from the vin pin.


texts:
I know there are a lot of questions about this topic, but I've tried everything and any possible guide online without success.

I want dim (increase and decrease the brightness) some leds (3.5 Watt each). To do that I'm using an Arduino Nano, a 10k potentiometer and an NPN transistor (TIP41).

I was able to drive the potentiometer as a switch: on/off. Now I want to control its brightness using the potentiometer. I don't get what I'm expecting because the led is always on except when the potentiometer is turned all the way on the right (where is connected Vcc).

This is the schematic:

This is my Arduino code:

int pinPotentiometer = 0;
int pinTransistor = 3;

void setup() {
  Serial.begin(9600);
  pinMode(pinTransistor, OUTPUT);
  pinMode(pinPotentiometer, INPUT);
}

void loop() {
  int potValue = analogRead(pinPotentiometer);
  int outValue = map(potValue, 0, 1023, 0 ,255);
  Serial.println(outValue);
  digitalWrite(pinTransistor, outValue);
  delay(100);
}

The potentiometer is working fine because I read from the serial values between 0 and 255.

Am I using the wrong transistor? Or maybe I'm using it in the wrong way?

NOTE: to test my circuit I'm using a small 5mm led and not the 3.5 Watt one so I don't have any external power source.

Many thanks!


texts:
I'm working on a little Arduino game project that uses neopixel strips as a display. Uploading every code change to the Arduino and testing it on the LEDs is slow and drains hardware lifetime.

Usually I test as much I can using the Serial Monitor, but I can't get it to clear from code which I learned is only possible e.g. when using a terminal. I did that, but it comes with other issues.

Is there a better way to test code on the dev machine instead of the Arduino?
Is there a best practice to have a Serial Monitor (or anything else) act like a display that I can actually refresh/clear? Serial.println() empty lines to scroll the content is not very practical.


texts: Where is all of the Arduino Documentation?

texts:
Aside from the main website, I have noticed that it is hard to find documentation for specific Arduino add-ons, such as (This is just one example):
https://www.amazon.com/gp/product/B00OGYXN8C/ref=ppx_yo_dt_b_asin_title_o04_s01?ie=UTF8&psc=1#descriptionAndDetails
Is this fairly normal or are you just expected to "just know what to do" with every Arduino component after a while? I realize that the IDE does have samples, but they don't always help.


texts: Library, instantiation of a class object

texts:
I am python experienced, an arduino noob, and absolutely no experience of C other than what has been forced upon me by arduino use.

I have just spent a day hammering google for the precise syntax of creating and using a class for user libraries, and have finally won.

However, I find that there are two forms that both seem to work for instantiating an object in the main program.

With my python experience, I find it easier to recognise the obj= style, used by Alan Zucconi in his examples, though the arduino.cc library tutorial on the Morse library uses the other form.

Is either preferrable, or are they equivalent in every way? Are there any subtle side effects of which I am unaware, that will bite me if the interfaces get more complicated, or some assumptions get corrected in future releases of the arduino IDE or compiler?

#include "Minimal_library.h"

// allocate buffer to be used
#define BUF_SIZE 40
char buff[BUF_SIZE+1];

// which of these two instantiation calls works?

// Minimal_library obj = Minimal_library(BUF_SIZE, buff);  //alanzucconi - works
Minimal_library obj(BUF_SIZE, buff);   //  Morse - that seems to work as well now
...

I presume that any private variables defined within the class become fully fledged persistent variables unique to the object created (it's been a long and frustrating day, not quite got around to testing the persistence or uniqueness yet, compiling without error, and then working, are enough for today!)


texts: Arduino struggling to power a large LED strip

texts:
I'm building a word clock and its a grid of 20x20 letters, each with its own LED (I know, its absurd for just a clock). I've recently got the LED's on a strip. Its the WS2812B type, just like the neopixels. There are 3 rolls of 5m strips and a single 1m strip. When I tried to power the 1m strip, everything worked perfectly and all looked quite lovely. But when I tried the 5m strip (just one of them), this happened: https://www.dropbox.com/s/5w1lok6wa7dfvzd/IMG_0046.MOV.mov?dl=0

If you didn't see the video I recorded of it, for a second or two after powering the arduino (uno) on, it works as expected but not long after it all stops the colors and fades to red, sometimes it just instantly jumps to it, like the second time in the video. I don't know what happened but all I can guess is that the arduino is not able to power the strip properly. Any ideas on what I should do to be able to power a total of 16m of these strips?


texts: Is there a practical way to broadcast and receive ascii payloads over ethernet or wifi?

texts:
How best might arduino nodes pass incoming serial ascii messages out as ascii network broadcasts for all others to receive and pass out through their serial ports?

ie: typing a msg from the IDE serial monitor of any ethernet node should cause that msg to be output to the serial monitors of all other nodes.


texts:
I'm trying to program my NodeMCU ESP8266 ESP-12E module with AT commands. However, whenever I try and flash to my ESP8266 using ESPTool, I get a 3-run stub fail error. Can anyone tell me why I get this error and how to fix it?
I have my suspicions that it might be the fact that I haven't pulled any of the pins, but I've been told that GPIO0, GPIO2, GPIO15, and CH_PD are all already pulled to the proper positions by default. If that may be the reason behind this error, could someone explain to me how exactly I should pull the pins, whether it be with a circuit or through code?
If it helps, I'm trying to follow along with this resource.
The only thing the ESP is connected to is the computer with USB.


texts: Library to set internal analog gain of the Arduino?

texts:
My original question was if there is a library that covers the internal comparator and differential and gain modes for the Arduino Uno, Mega 2560, Leonardo, Due, Zero, M0.
The answer is obvious: "No". To my surprise there is not even a start to make it and neither a collaboration to gather usefull code.

If you know pieces of code (Arduino compatible and documentation for which pins) for the analog comparator and gain, then please tell me about it, and I put them in this list.

analogComp, a library to manage the analog comparator.
To use the analog comparator for the ATmega8, Arduino Uno, Leonardo, Mega 2560, ATtiny85, and others. A routine is called with an interrupt every time a particolar condition happens.
Arduino Differential ADC and Gain ADC
A file "wiring_differential.c" should be added to the Arduino files. Functions "analogReadDiff" and "analogReadGain" will be added. For the Arduino Leonardo and the Arduino Mega 2560.
Nick Gammon: Using the Arduino Analog Comparator
A simple example of a comparator mode for the ATmega328.
Application Note AT11480: Analog Comparator Application Examples
Using the Analog Comparator for SAM D (that includes the ATSAMD21 of the Arduino Zero and M0) processors.


texts: Is it possible to check for correct architecture on OTA update (ESP32 or ESP8266)?

texts:
Having a skech running on ESP8266 as well as ESP32 with the ability to update via OTA, uploading the wrong binary (upload to ESP8266 compiled for ESP32, and vice versa) leads to crashing the MCU and not being able to do OTA Updates any more.
The Update is done in the simple usual way: Upload binary file and call the methods from the Update Class (begin(), write(), and end()).
Is there any way to check if the uploaded file matches the architecture of the MCU before starting the update?
Edit:
Both the ESP8266 and the ESP32 Updater class check for an "IMAGE_MAGIC" value in the upload header; but that is defined as "ESP_IMAGE_MAGIC = 0xe9" in both cores. So none of them will refuse to update the wrong one.
Edit 2:
Found a simple workaround that satisfies our needs at the moment: As the arduino IDE saves the binaries with a name like <sketch_name>.<board_name>.bin, we just compare the board name as part of the uploaded filename: if (upload.filename.indexOf(MATCH) > 0) ..., where MATCH is the respective board name. As they are pin compatible, we use "d1_mini.bin" and "d1_mini32.bin".
Edit 3:
When the webserver tries to abort the upload with 403 Forbidden (because of wrong file), the browser continues to send data until the upload is done. After that, it displays the error message. Thus, even when the filename does not match, it is a waste of time and bandwidth. The only possibility to avoid this is to do a server.client().stop(), but then the browser will not display the message sent, just something like "connection broken". This does not confirm with the respective RFCs.
This is not really a final solution, so I'ld appreciate any better idea.
Richard


texts: Arduino Due not executing code after power on

texts:
My Arduino Due does not execute its code when powered on after being powered off for ten seconds or longer. I have to press the reset button for the code to execute.

I've read some older threads about a firmware issue and saw people doing solder jobs on their boards to fix it.

My question is, does this issue happen with all/any Arduino Due boards? Are just some clones (like mine) affected and the original works fine?

What's the best way to fix this problem? In this state the board serves no purpose anymore and I've downgraded to the Uno for now.

EDIT: Adding picture and link to the board used.
https://www.amazon.de/gp/product/B016D5KYF6/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1


texts: IO with port manipulation while not interfering with i2c

texts:
I'm using an Attiny84 with the Tiny Core.
I'm try to use port manipulation to write the lower four bits of port A. I'm using i2c which occupies bits 5 and 7.

How can I write only to the lower 4 bits to avoid interfering with the i2c?


texts: Share battery pack with Arduino and DC motors

texts: I used 6 rechargable AA batteries (total 7.2V) to power my Arduino (UNO R3) Car's two DC Motors (using L293D IC as motor driver). I used separate 9V battery to power arduino itself. But I want to share same 6 battery pack to power my arduino via barrel jack. Please suggest me how can I do this? What precautions Should I take? Like decoupling capacitors or any other?


texts: Using LM70 temperature sensor with Arduino

texts:
I am trying to sense the temperature using the LM70 temperature sensor with an Arduino Mega. As you can see in the Datasheet, it uses the SPI protocol. I have made the following connections (VSSOP-8 Package):

SI/O pin --> Pin 50 Arduino Mega.
SC pin --> Pin 52 Arduino Mega.
CS pin --> Pin 53 Arduino Mega.
V+ pin --> 3.3V Arduino Mega.
GND pin --> GND Arduino Mega.

My code does not work (it does not print the right temperature), and I think it can be for two reasons:

I am not reading correctly the information from the sensor. It sends 16 bits, from which the 11 first bits store the data for the temperature.
I am not calculating the temperature in the right way.

This is my code:
// the sensor communicates using SPI, so include the library:
#include <SPI.h>

void setup() {
  pinMode(51,OUTPUT); //MOSI
  pinMode(50,INPUT); //MISO
  pinMode(52,OUTPUT); //CLOCK PIN
  digitalWrite(53,HIGH); //slave select stays high. When we set this to low, the sensor will start to send data.
  SPI.begin();
  Serial.begin(9600);

  //time to set up
  delay(500);
}

void loop() {
    //enable Slave
    digitalWrite(A0,LOW); //Enable communication with slave
    delay(500); //wait for conversion

    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;
    Serial.println(temperature); //display temperature on serial monitor

    //disable Slave
    digitalWrite(53,HIGH); //set to High again
}

Please, if you see something wrong in my code, let me know.
Thank you in advance.


texts:
I want to transmit and receive data with the help of NRF24l01 modules. I tried to deliver joystick values from UNO to UNO but I have trouble about it.

In receiver side I have only zeros. I have been connect pins according to pin out orders.

ce--9
csn----10
sck----13
mosi----11
miso-----12

on both side. I am using module adapter to provide constant current and feeding with 3.3 volt and 5 volt another one. Both did not work. I bought new modules and adapters and connected 3.3 volt but nothing changed. I could not understand the problem help me please. Here is are my sketches:

RECEIVER

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#define CE_PIN   9
#define CSN_PIN 10
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
int data[3];
void setup()
{
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.openReadingPipe(1, pipe);
  radio.startListening();
  radio.setPALevel(RF24_PA_MAX);
}

void loop() {
  if ( radio.available() ) //Eğer sinyal algılarsan...
  {

    radio.read( &data, sizeof(data) );

    Serial.print("data[0]=");
    Serial.println(data[0]);
    Serial.print("data[1]=");
    Serial.println(data[1]);
    delay(300);
    radio.stopListening();

  }
  else {
    Serial.println("no signal");
  }
}

TRANSMITTER

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#define PIN_ANALOG_X 0
#define PIN_ANALOG_Y 1
#define CE_PIN   9
#define CSN_PIN 10
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
int data[2];

void setup() {

  // Start serial because we will observe values at serial monitor
SPI.begin();
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(pipe);
  radio.setPALevel(RF24_PA_MAX);
}

void loop() {

  // Print x axis values

  Serial.print("x: ");

  Serial.println(analogRead(PIN_ANALOG_X));

  // Print y axis values

  Serial.print("y: ");

  Serial.println(analogRead(PIN_ANALOG_Y));
  data [0] =map( analogRead(PIN_ANALOG_X),0,676,0,255);
  data [1] = map(analogRead(PIN_ANALOG_Y),0,676,0,255);

 radio.write( &data, sizeof(data) );
  Serial.println("data0");
  Serial.println(analogRead(PIN_ANALOG_X));
  Serial.println("data1");
  Serial.println(analogRead(PIN_ANALOG_Y));

Serial.println(data [0]);
Serial.println(data [1]);
  // Some delay to clearly observe your values on serial monitor.

  delay(300);

}


texts: How to store incoming serial string in arduino?

texts:
In my recent project, I am working with serial data. Till now, I'm able to receive data and display on LCD. Now, suddenly I can't get any serial data. Nothing display on LCD.

My incoming string is:

{"Action":"ONE","TPS":"0.40","MAP":"0.95","LOAD":"14"}

And my code is below:

#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin)
    {
      response += (in);
    }

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  lcd.setCursor(0, 0);
  lcd.print(response);
}


texts: I am planning for a project but i am stuck with a task and hope you could help me. My work is to note down a number which is actually a set of readings displayed on a meter and store it on a arduino. My problem is that i need a detection technique so that i could record the number or extract the number from a image or video if u suggest to use a camera or recorder or purely can be a sensor. Thank you guys, waiting for you.


texts: Question regarding Servo including Serial monitor display

texts:
I tried to make code following your instruction about mills,
and it looks like this. Unfortunately, it is not working. Is there problem with my code?

Here is my code:

#include <LiquidCrystal.h>
#include<Servo.h>

Servo myservo;  // create servo object to control a servo

// These constants won't change. They're used to give names to the pins used:
const int analogInPin1 = A0;  // Analog input pin that the photosensor is attached to
const int analogInPin2 = A1;  // Analog input pin that the photosensor is attached to
const int analogInPin3 = A2;  // Analog input pin that the photosensor is attached to
const int analogInPin4 = A3;  // Analog input pin that the photosensor is attached to
int sensorValue1;
int sensorValue2;
int sensorValue3;
int sensorValue4;
unsigned long m;

//declare counter as an input
int Chactr =0;
int Disctr =0;

byte state;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(0);  // back to 0 degrees.
  delay(1000); // wait for a second.
  pinMode(13, OUTPUT); // initialize digital pin 13 as an output.
  Serial.begin(9600);  // initialize serial communications at 9600 bps:
  lcd.begin(16,2);

  delay(5000);
}

void loop() {

  // read the analog in value:
  sensorValue1 = analogRead(analogInPin1);
  sensorValue2 = analogRead(analogInPin2);
  sensorValue3 = analogRead(analogInPin3);
  sensorValue4 = analogRead(analogInPin4);

  delay(3000);

  // print the results to the Serial Monitor:
  Serial.print("sensor1 = ");
  Serial.print(sensorValue1);
  Serial.print("\n");

  Serial.print("sensor2 = ");
  Serial.print(sensorValue2);
  Serial.print("\n");

  Serial.print("sensor3 = ");
  Serial.print(sensorValue3);
  Serial.print("\n");

  Serial.print("sensor4 = ");
  Serial.print(sensorValue4);
  Serial.print("\n");

  Serial.print("Led State:  ");
  Serial.println(state);
  Serial.print("\n");

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250)
  {
    m=(millis()+60000);
  }

  if(sensorValue1 <=568 && sensorValue2 <=519 &&sensorValue3 <=418 && sensorValue4 <=249)
  {
    m=0;
  }

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250 && m==millis())
  {
    state=1;
    delay(5000);
    digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
    delay(5000); // wait for a second

    myservo.attach (9);
    myservo.write(30);
    delay(3000);
    myservo.write(0);
    delay(3000);

    myservo.detach ();
    delay (1000);

    Disctr = Disctr + 1;

    delay(900);

    Serial.print("Battery Full: Discharge ON");
    Serial.print("\n");
  }
  else if (sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4 ==0 )
  {
    m=(millis()+60000);
  }

  if(sensorValue1 >=1 && sensorValue2 >=1 && sensorValue3 >=1 && sensorValue4 >=1)
  {
    m=0;
  }

  if(sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4  ==0 && m==millis())
  {
    state=0;
    delay(5000);
    digitalWrite(13, HIGH ); // turn the LED On by making the voltage high
    delay(5000); // wait for a second

    Chactr = Chactr + 1;
    delay(900);

    Serial.print("Battery Empty: Charging ON");
    Serial.print("\n");
  }
  {
    lcd.setCursor(0,0);
    lcd.print("Charge Cycle: ");

    lcd.setCursor(13,0);
    lcd.print(Chactr);

    lcd.setCursor(0,1);
    lcd.print("Discha Cycle: ");

    lcd.setCursor(13,1);
    lcd.print(Disctr);

    delay(1000);
  }
}


texts: How can I implement a parking counter with multiple entrances and exit?

texts:
I'm relatively new to arduino projects and am trying to solve a real world problem on a parking lot space counter.
My Idea is to have a sensor placed on the entrances and exit to count the total number of cars in the parking lot.
Now there are several codes online but they only implement for 1 entrance.

Scaling for 4 entrances:

  Would it be ideal to implement 1 main unit with multiple cables running to each sensors placed on the entrances and exits of the parking lot.

Given that the parking lot is huge:

  Is there a wireless way to transmit data from each sensor to the central unit ?

I'm welcoming any recommendations regarding this project.

EDIT:
This is for an actual prototype. I've scoped around the garage to find that I only need  multiple entry exit (2) system for the ground floor. Rest of the two floors have their own 1 entry and exit points.
The entrance and exit are the same point so I was thinking of a bidirectional sensor.

  Does 10 feet of width pose a problem for the sensor ?
  Could I instead use two bi-directional sensors placed on either sides of the entry and exit, and then hook them up to the same input in the Arduino ? So incase 1 misses the other one registers.

Edit 2: The parking deck is big enough to hold about 20-25 cars on each of the 3 floors. I don't know the exact measurement though

  Besides Sensors could I use a wire on the floor to register when a car crosses over ? Would that be easier?


texts: Can't make Quadratic Programming Library (EigenQP) library work in NodeMCU

texts:
I have been trying to use find a Quadratic problem solver library which is compatible with Eigen library for my NodeMCU board (In my code I have to deal with a lot of matrix operations, that's why I chose Eigen)
I found the following one by jarredbarber : [https://github.com/jarredbarber/eigen-QP][1]
For some reason, I'm not being able to use the QP library in my nodemcu. Here is one very simple demonstration I've been trying to establish. But it throws away some errors, I can't figure why :
In my sketch for the NodeMCU:
#include <Arduino.h>
#include <EEPROM.h>
#include <Wire.h>

#include <iostream>
//#include<ctime>        //srand()
#include<cstdlib>

#define _USE_MATH_DEFINES
#include <cmath>        // for using M_PI, Trig. functions (sin/cos/tan)
using namespace std;

//#include <ArduinoSTL.h>
#include "Eigen313.h"
using namespace Eigen;

#include "eigen-qp.hpp"
using namespace EigenQP;

//#define PI 3.1416

void setup() {
  // put your setup code here, to run once:
  Serial.println("Lets start!!");
int N=4;
float gamma =10000;
float safety_radius=0.1200;
  Eigen::Matrix<float,Dynamic,Dynamic> Q(2*N,2*N); Q.setIdentity();
  cout<<Q<<endl;
  Eigen::Matrix<float,Dynamic,1> c(2*N,1);
      c<<0,
         0,
    0.0086,
    0.0847,
   -0.1499,
    0.0687,
    0.0083,
   -0.0867;

    Eigen::Matrix<float,Dynamic,Dynamic> A(6,2*N);
  A<<0.0655,0.6483,-0.0655,-0.6483,0,0,0,0,
    -0.5839,0.6251,0,0,0.5839,-0.6251,0,0,
    -0.5587,-0.0275,0,0,0,0,0.5587,0.0275,
     0,0,-0.6494,-0.0232,0.6494,0.0232,0,0,
     0,0,-0.6242,-0.6758,0,0,0.6242,0.6758,
     0,0,0,0,0.0252,-0.6526,-0.0252,0.6526;
std::cout<<"A:\n"<<A<<endl;
    Eigen::Matrix<float,Dynamic,1> b(6,1);
b <<7.7197,
   47.8600,
    2.6007,
    7.5770,
   76.6646,
    7.8461;

    A=-A;
    b=-b;
Eigen::Matrix<float,Dynamic,1> x(2*N,1);
yield();
delay(2000);
        //boost::timer::auto_cpu_timer t;
        //for (int ii=0; ii < 8; ii++)
        //QPIneqSolver::solve(&H,&f,&A,&b,&x);
EigenQP::quadprog<float,Dynamic,Dynamic>(Q,c,A,b,x);
std::cout<<x<<endl;

}

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

}

It compiles fine, but in the serial monitor, these show up :
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3584, room 16
tail 0
chksum 0xb0
csum 0xb0
v2843a5ac
~ld

I tried to run the same code in codeblocks software in my computer, it works fine though.
PS: This is the first time I've ever posted any topic in this forum, please inform me if I've violated any guideline for the post..
Thanks in advance.
[1]: https://github.com/jarredbarber/eigen-QP


texts:
I'm frustrated I feel like I am 90% there but my computer will not recognize the ATtiny167. Here i9s the list of things I have completed/tried using Windows 10 and Arduino 1.8.6;

                  1) Installed Driver USB Bootloader is complete
                  2) Device Management I see the device
                  3) Arduino Sketch select 16.5 MHz board in parameters
                  4) Led on the board flashes sound beeps and stops flashing
                  5) "Device not recognized"
                  6) I have rebooted many times. I deleted everything and started over again with same
                      results
                  7) Used a 3rd party software to look at my USB ports it see the device
                   I have tried more than one device as well

         I'm stuck at this point. I've tried running example programs however the device is not recognized.

Any suggestions?


texts: Convert String data To char Array in Arduino

texts:
I'm able to get json data and storing in String object, now i want to convert string into Char Array for parsing json data

I'm tried with this code, but it is not responding

      String data = http.getString();   //Get the request response payload
      Serial.println(data);                     //Print the response payload
      int len=data.length();
      Serial.println(len);

      char  buf[len + 1];
      data.toCharArray(buf, len + 1);
      int bufLength = sizeof(buf);
      Serial.println(bufLength);   //Printing nothing


texts:
Following is the code I found in Arduino example files. It compiled fine on Arduino UNO. But there was an error when I tried to compile it for nodeMCU 1.0(ESP 12E Module).

#include <TimerOne.h>
void setup() {
  pinMode(13,OUTPUT);
  Timer1.initialize(5000000);//5 sec
  Timer1.attachInterrupt(timerIsr);
}
void loop() {}
void timerIsr(){
  digitalWrite(13,!digitalRead(13));
}

Following was the error message. I had this kind of error previously on OneWire.h and I solved it by replacing the OneWire.h library with another OneWire.h library that was made especially for nodeMCU.

Error msg:

Arduino: 1.8.3 (Windows 8.1), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

In file included from D:\iox Prime\TEC project\code\building modules\timerIsrDemo\timerIsrDemo.ino:1:0:

C:\Program Files (x86)\Arduino\libraries\TimerOne/TimerOne.h:39:20: fatal error: avr/io.h: No such file or directory

 #include <avr/io.h>

                    ^

compilation terminated.

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I searched the library everywhere in the internet to solve this error but end up with no success. I wish somebody modifies the existing library for me. Thank you for the help.


texts:
I am trying to measure AC power using an Arduino with an Atmega328p.
In summary, I want to use timer1 to make an interrupt every 400us where I measure two ADC channels (A0 and A1) and put them into an array. The problem is that instead of measuring five mains periods (mains frequency = 50Hz so 20ms * 5), I get instead 13 of these periods (260ms). What am I doing wrong?

volatile int sample_incremental = 0;

void setup() {
      Serial.begin(115200);
      pinMode(voltagePin, INPUT);
      pinMode(currentPin, INPUT);
      set_sample_interrupt();
      sei();
    }

void set_sample_interrupt() {
  //Count to 400us
  OCR1A = 99;
  //Mode 4, CTC
  TCCR1B |= (1 << WGM12);
  //Enable interrupt
  TIMSK1 |= (1 << OCIE1A);
  //Prescaler 64
  TCCR1B |= (1 << CS11) | (1 << CS10);
}

ISR (TIMER1_COMPA_vect) {
  // action to be done every 400 usec
  current_sample[sample_incremental] = analogRead(currentPin) - 504;
  voltage_sample[sample_incremental] = analogRead(voltagePin) - 512;
  if (sample_incremental < (SAMPLES * PERIODREADS))
    sample_incremental++;
  else {
    //Disable interrupt
    TIMSK1 &= ~(1 << OCIE1A);
    sample_incremental = 0;
    finishedReading = true;
  }
}

Where after I do one reading, I stop the interrupt, and SAMPLES * PERIODREADS = 250.


texts:
i've got the following problem i'd like to get solved and i'm breaking my head, so please help!

I have a rectangle with the following size 40 cm * 50 cm. On each corner of this rectangle I placed a Piezo element (it's an electronic element which measures the vibration)

The rectangle is defined as followed: the left upper corner = A the left lower corner = B the right lower corner = C the right upper corner = D

I'm trowing a ball on the surface and I'd like to calculate it's X and Y axis. The outcome of the piezo elements are as followed:

A,B,C,D - 0 lowest vibration, 1023 highest vibration These values can be mapped to a number I can decide, so that means I can make it whatever we need it to be. Example: map 0,1023,0,100, meaning the new mapping will be 0 - 100.

I found a possible solution here: http://mathafou.free.fr/pbg_en/sol114.html The problem I got is that i don't know where the ball will be and therefor I don't know the angle it will fall on.

The thing I do now is:

Example: We trow the ball. The outcome could be ABC or what would be best ABCD results.

I thought Pythagoras could come in handy here. The thing I did was: A*A+B*B=C*C (to get the square calculation done) A+B = AB, B+C = BC, A+C= AC, (to get the sides of a triangle) AB*BC=AC (We don't know AC but we can square root the outcome of AB*BC)

But then i realised I just know how long the side is and I still don't know where the ball landed :(

The following I already implemented to scale it when it works (maybe not relevant now) A+B+C+D = Total outcome we can possibly get at that point (as we are relying on vibration) A,B,C,D/Total = the scale we need to calculate with

I call this A1,B1,C1,D1 so I can re-use this in the code The reason I do this, is the follow up I need it for. Im going to use a projector to project a video on the exact X/Y position. But that's not relevant I guess for now.

I'm programming this in Processing 2 : http://processing.org


texts: Multiple shift registers, 16 bit numbers

texts:
Currently working on understanding shift registers and traing to display binary number from 65535 to 0 on a 16 LED's.  Below you can see schematics I am using.

The code I am using is

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int numberToDisplay=65535;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {

    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

    digitalWrite(latchPin, HIGH);
    delay(500);
  }

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 16; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (15 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

Problem is when I change numberToDisplay from 0 to 225, everything works and LEDs are lighted correspondingly (if numberToDisplay=225 all red lights are on). But if numbers are bigger than 225 everything just stops working and nothing lights up.

Thank you in advance


texts: Bluetooth HM-10 in central mode bonding with another bluetooth device

texts:
I have a bluetooth HM-10 configured in central mode. I have successfully connected it to another bluetooth device (a hexiwear bluetooth wearable). The problem now is that the hexiwear requires me to provide a 6 digit pin before it will bond with my HM-10.

Would anyone know the AT command that I could use to send the 6 digit pin from the HM-10 to the hexiwear?

Thank you.


texts:
I need to make for school a project. That when i hold a button it fades. But when you let go the button it needs to stop immediately. But when i you hold the button again it needs to start again with fading but the brightness needs to start from 0. I have a program but when i press again it just starts from the previous brightness. Pls help. This is my code:

int led = 9;
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
    pinMode(led, OUTPUT);
}
void loop() {
  int val = digitalRead(2);
  Serial.println(val);
if (val==HIGH){
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount; }
  delay(100);
}
else{

  digitalWrite(9, LOW);
}
}


texts: Is it possible to query (or otherwise detect) if Arduino is connected to 60 NeoPixel strip vs 144 strip?

texts: Is there any way to have an arduino detect how many LEDs are on a connected strip? I have a 60 strip and 144 strip. The code is identical for both, aside from setting the number of LEDs in a variable to iterate over.


texts:
I have a motion sensor that triggers an LED and buzzer. That part works fine and it displays Motion detected in the serial monitor. I'm trying to get the LCD to print that as well but I can't get it to work. The LCD backlight turns on but that's it. At first I tried with the LCD16x2 I2C and now I'm trying with the regular LCD16x2. Here's my code:

#include <LiquidCrystal.h>

const int MOTION_SENSOR_PIN = 7;   // Arduino pin connected to the OUTPUT pin of motion sensor
const int BUZZER_PIN        = 3;   // Arduino pin connected to Buzzer's pincon
int motionStateCurrent      = LOW; // current  state of motion sensor's pin
int motionStatePrevious     = LOW; // previous state of motion sensor's pin
LiquidCrystal lcd(12, 11, 6, 5, 4, 2);

void setup() {
  Serial.begin(9600);                // initialize serial
  pinMode(MOTION_SENSOR_PIN, INPUT); // set arduino pin to input mode
  pinMode(BUZZER_PIN, OUTPUT);          // set arduino pin to output mode
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
}

void loop() {
  motionStatePrevious = motionStateCurrent;            // store old state
  motionStateCurrent  = digitalRead(MOTION_SENSOR_PIN); // read new state

  if (motionStatePrevious == LOW && motionStateCurrent == HIGH) { // pin state change: LOW -> HIGH
    Serial.println("Motion detected!");
    if (Serial.available()) {
      delay(0);
      lcd.clear();
      while (Serial.available() >0) {
         lcd.print("Motion detected!");
      }
    }
    digitalWrite(BUZZER_PIN, HIGH); // turn on
  }
  else
  if (motionStatePrevious == HIGH && motionStateCurrent == LOW) { // pin state change: HIGH -> LOW
    Serial.println("Motion stopped!");
    if (Serial.available() > 0) {
      delay(0);
      lcd.clear();
      while (Serial.available()) {
         lcd.print("Motion stopped!");
      }
    }
    digitalWrite(BUZZER_PIN, LOW);  // turn off
  }
}


texts: ATMega1284 and Relative Humidity libraries

texts:
I am trying to use some Relative Humidity sensors (DHT11 and DHT22) with the ATMega1284 processor on a breadboard. I use libraries from Arduino playground (dht.h), Adafruit (DHT.h) and others. Even though both sensors and libraries work fine with Arduino Uno and Mega, they fail with ATMega1284, which produces an INVALID_VALUE error.

Connections are double checked, and other libraries such as Wire, OneWire etc work fine.

Does anyone have any experience with the ATMega1284 processor, or any suggestions?


texts: home automation - What's a compact way to control a light switch with Arduino without interacting with high voltage?

texts:
To be clear, this question is not about physically wiring into the light switch to control the lights - simply pressing on the switch from the outside. I apologize in advance if my electrical vocabulary isn't up to par - I'm very new to this.

I have been developing an Android app that allows me to control Particle Photon boards over the internet, and I have already installed a board that turns my computer on and off. However, I am researching ways to automate the lights (ceiling lights, not lamps) without interacting with high voltage. I have not been able to find any good information.

Does anybody have any advice?


texts: I want to begin with arduino programming

texts:
I want to start programming with the Arduino Uno, but I don't know where to start or what a good start is. I can program a bit in c#, but I red that you have to program in c++.

Any idea's where to start?

Thanks!


texts: Connection Pro-Mini & ESP8266 using Serial

texts:
I wish to create a system consists of WEMOS mini & Pro-Mini sharing info using Serial ( one MCU is dedicated to react input-output, and second for MQTT commands ) sharing same Power input. From what I read in tutorials, at boot Serial wires have to be disconnected, in order to accomplish boot.
A) is that true that at boot Serial has to be disconnected?
B) is there a way that 2 MCU can be connected at all times, including reboot when needed ( such as power failures ) ?


texts: How can Arduino's 8 bit Microcontrollers handle C++

texts:
I have just started getting into Arduino and c++ programming!

For all the talk on the internet about c++ being incompatible with 8-bit and even 16-bit microcontrollers, how is it that Arduino Microcontrollers can safely handle c++ code, in terms of the ram usage? Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) that (I believe) are very ram-usage-intensive?

Cheers!


texts:
I bought a BMP280 and it looks like this:

How can I connect BMP280 to Arduino Uno?
I tried the following examples on the web, but they didn't work.
I used  this library, connecting the PINS in this way:

VCC  ->  3.3V
GND  ->  GND
SCL  -> 13
SDA  -> 12
SDO  -> 11

But the sensor did not initialize.


texts: Why is Arduino resetting while driving motors?

texts:
I am driving motors for my line-follower project . The circuit schematic is given below

The power source is a 11.1V 2200mAh 25C Lipo . Practically the cells give 11.5-12V. I used a switching buck regulator to step down the voltage. However , when i run my robot on track after few seconds,the arduino tends to reset and run again. This problem typically arises when i drive the motors at higher PWM(above 180 on analogWrite function). Since i use PID, limiting the PWM means i have to drive at lower speeds which i do not want.

I am providing links for the items i used for my circuit:

buck converter;
motor driver;
IR sensor module;
DC motors.

The sensor array draws 150mA at peak. Any suggestions as to where the problem might lie would be of great help. Thank you .

EDIT 1: Changed the input voltage Vin to 7.9V through the buck converter .
        The problem still persists .


texts: How can I connect an arduino to a raspberry pi via an HC 05 bluetooth module and transmit data?

texts:
I am currently undertaking a project where I am attempting to build a bluetooth thermometer using an arduino.
I have the temperature sensor working and returning temperature readings via a usb connection to the serial monitor in the Arduino IDE using the following code.

#include <OneWire.h>
#include <DallasTemperature.h>
#include "Timer.h"

Timer t;

// Data wire is plugged into pin 10 on the Arduino
#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

DeviceAddress insideThermometer = { 0x28, 0x94, 0xE2, 0xDF, 0x02, 0x00, 0x00, 0xFE };

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  // Start up the library
  sensors.begin();
  // set the resolution to 10 bit (good enough?)
  sensors.setResolution(insideThermometer, 10);
  int tickEvent = t.every(3000,doTempReading);

}

void loop()
{
    t.update();
}

void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00) {
    Serial.print("Error getting temperature");
  } else {
    Serial.print("C: ");
    Serial.print(tempC);
  }
}

void doTempReading()
{
  delay(2000);
  Serial.print("Getting temperatures...\n\r");
  sensors.requestTemperatures();

  Serial.print("Inside temperature is: ");
  printTemperature(insideThermometer);
  Serial.print("\n\r");
}

I now want to try and transmit the readings via a bluetooth connection using the HC 05 module to a raspberry pi which will record the data.

I have done a lot of research and tried several different techniques and can't understand how to go about it.

What mode does the HC 05 need to be in? (Command AT/slave/data/etc.)
How should it be wired (I have found several different methods using various resistors and capacitors and unsure which to follow).
How should I pair it with the Raspberry pi?

Thanks in advance for any help.


texts: Motor driver shield l239D should be giving enough power but it doesn't

texts:
I am doing a line follower robot using motor driver shield l239D stacked with an Arduino uno to run 2 DC motors and two infrared sensors. I am supplying 12V to the motor driver shield trough three 18650 batteries.
The point is the car was working fine and it followed the line but  two days ago it stopped working after one week of working fine...
When the two DC motors and two sensors are connected the motors don't move they just buzz(the sound it makes when it's not getting enough power), it works sometimes a little bit...

Basically the car only works with no sensor connected. So I made measurements with the multimeter and I got this:

The three batteries:12.62V

The shield receives: 12.39V only with the two sensors connected and the motors disconnected.

The shield with the motors and two sensors connected:12.28V.

And when I measured how much the motors where receiving I got 0V! In both of them...

With just one motor and the sensors connected the motor started buzzing and I got 0.07V till the sound stopped and I got zero again.

Sometimes the motors work a little bit sometimes they just buzz and some times they don't buzz at all...

I see that the batteries are fine and they can deliver enough current for everything to work but the motors don't receive almost anything!!!

Can you help me and tell me suggestions of what I need to do please? I searched and asked a lot but haven't found anything that helps...
Here is my car and my circuit.


texts: Is it possible to build a battery charger with just an arduino UNO board (and perharps some passive components)?. It's a 3.7V 550 mAh LiPo Battery. I understand I need to monitor the charge and the current flowing into the battery to properly (as in safely) charge it.


texts:
Consider this function:

void noteOn(uint8_t pitch) {
  midiEventPacket_t noteOn = {0x09, 0x90 | 9, pitch, 127};
  MidiUSB.sendMIDI(noteOn);
}

midiEventPacket_t is defined as:

typedef struct
{
    uint8_t header;
    uint8_t byte1;
    uint8_t byte2;
    uint8_t byte3;
}midiEventPacket_t;

The first nibble of the first byte of a MIDI message is the command: 0x90 ["note on"] and the second nibble is the MIDI channel: 9, so what's sent over the wire should be 0x99 meaning "Note On, channel 9", with the two more bytes representing the pitch and the velocity.

My question is, why do all of the examples start with: {0x09, 0x90 | 9,? I'm not understanding the use of the struct here. Intuitively, I thought I would need: {0x90 | 9, pitch, 127, 0}. Why do all of the examples have that seemingly strange syntax?

EDIT

After getting a great explanation below, here's my new function!

void noteOn(uint8_t pitch) {
  midiEventPacket_t noteOnPacket;
  noteOnPacket.header = USB_CABLE_NUMBER | (MIDI_NOTE_ON >> 4);
  noteOnPacket.byte1 = MIDI_NOTE_ON | CHANNEL;
  noteOnPacket.byte2 = pitch;
  noteOnPacket.byte3 = MIDI_BUTTON_ON_VELOCITY;
  MidiUSB.sendMIDI(noteOnPacket);
}


texts: MPU-6050, why is pitch, yaw and roll data not being consistent (value keeps getting higher/lower when it is stable)?

texts:
I recently bought a MPU 6050 that I plan to use with a drone. However I face some difficulties now because the MPU is not giving me steady results.

The results (pitch, roll, yaw) i get are not consistent. If I for example keep the chip stable on a table the value keeps increasing/decreasing even though it is not being touched/moved.

I also seem to get different results if i restart it even though i use it at the same angles.

Is something off with my code or is there anything else I need to do in order to fix this issue?

Appreciate any help I can get! :)

Here is my current code:

#include <Servo.h>
#include <Wire.h>

int gyro_x, gyro_y, gyro_z;
long acc_x, acc_y, acc_z, acc_total_vector;
int temperature;
long gyro_x_cal, gyro_y_cal, gyro_z_cal;
long loop_timer;
int lcd_loop_counter;
float angle_pitch, angle_roll;
int angle_pitch_buffer, angle_roll_buffer;
boolean set_gyro_angles;
float angle_roll_acc, angle_pitch_acc;
float angle_pitch_output, angle_roll_output;

void setup() {

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

setup_mpu_6050_registers();
for (int cal_int = 0; cal_int < 2000 ; cal_int ++){

read_mpu_6050_data();
gyro_x_cal += gyro_x;
gyro_y_cal += gyro_y;
gyro_z_cal += gyro_z;
delay(3);
}

gyro_x_cal /= 2000;
gyro_y_cal /= 2000;
gyro_z_cal /= 2000;
loop_timer = micros();

}

void loop(){

read_mpu_6050_data();

gyro_x -= gyro_x_cal;
gyro_y -= gyro_y_cal;
gyro_z -= gyro_z_cal;

angle_pitch += gyro_x * 0.0000611;
angle_roll += gyro_y * 0.0000611;

angle_pitch += angle_roll * sin(gyro_z * 0.000001066);
angle_roll -= angle_pitch * sin(gyro_z * 0.000001066);

acc_total_vector = sqrt((acc_x*acc_x)+(acc_y*acc_y)+(acc_z*acc_z));
angle_pitch_acc = asin((float)acc_y/acc_total_vector)* 57.296;
angle_roll_acc = asin((float)acc_x/acc_total_vector)* -57.296;

angle_pitch_acc -= 0.0;
angle_roll_acc -= 0.0;

if(set_gyro_angles){
angle_pitch = angle_pitch * 0.9996 + angle_pitch_acc * 0.0004;
angle_roll = angle_roll * 0.9996 + angle_roll_acc * 0.0004;
}
else{
angle_pitch = angle_pitch_acc;
angle_roll = angle_roll_acc;
set_gyro_angles = true;
}

Serial.println(angle_pitch_output);
Serial.println(angle_roll_output);

while(micros() - loop_timer < 4000);
loop_timer = micros();
}

void read_mpu_6050_data(){

Wire.beginTransmission(0x68);
Wire.write(0x3B);
Wire.endTransmission();
Wire.requestFrom(0x68,14);
while(Wire.available() < 14);
acc_x = Wire.read()<<8|Wire.read();
acc_y = Wire.read()<<8|Wire.read();
acc_z = Wire.read()<<8|Wire.read();
temperature = Wire.read()<<8|Wire.read();
gyro_x = Wire.read()<<8|Wire.read();
gyro_y = Wire.read()<<8|Wire.read();
gyro_z = Wire.read()<<8|Wire.read();

}

void setup_mpu_6050_registers(){

Wire.beginTransmission(0x68);
Wire.write(0x6B);
Wire.write(0x00);
Wire.endTransmission();

Wire.beginTransmission(0x68);
Wire.write(0x1C);
Wire.write(0x10);
Wire.endTransmission();
Wire.beginTransmission(0x68);
Wire.write(0x1B);
Wire.write(0x08);
Wire.endTransmission();
}


texts: My RTC DS1307 isn't returning any information. It seems to be stuck in the isrunning() function. Does anyone have debugging tips?

texts:
I'm using an RTC DS1307 to keep track of time for long periods. It seems to be stuck in a function. I'm using the RTClib suggested by adafruit.

How can I get it unstuck and get values returned? Are there any debugging or troubleshooting tips that would be helpful?

Referencing this excerpt for the code I'm running.

void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) { //// **Where I think my code errors.**
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

This is the example code modified slightly to increase logging, included with RTClib. It's for the DS1307.

Currently the output from the serial port is as follows:

  RTC is found.

I changed the code to the below:

    // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {
      while (!Serial); // for Leonardo/Micro/Zero

      Serial.begin(9600);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      } else {
        Serial.println("RTC is found.");
      }

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      } else {
        Serial.println("RTC is RUNNING.");
      }
    }

    void loop () {
        DateTime now = rtc.now();

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(" (");
        Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
        Serial.print(") ");
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();

        Serial.print(" since midnight 1/1/1970 = ");
        Serial.print(now.unixtime());
        Serial.print("s = ");
        Serial.print(now.unixtime() / 86400L);
        Serial.println("d");

        // calculate a date which is 7 days and 30 seconds into the future
        DateTime future (now + TimeSpan(7,12,30,6));

        Serial.print(" now + 7d + 30s: ");
        Serial.print(future.year(), DEC);
        Serial.print('/');
        Serial.print(future.month(), DEC);
        Serial.print('/');
        Serial.print(future.day(), DEC);
        Serial.print(' ');
        Serial.print(future.hour(), DEC);
        Serial.print(':');
        Serial.print(future.minute(), DEC);
        Serial.print(':');
        Serial.print(future.second(), DEC);
        Serial.println();

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


texts: What is a faster alternative to parseInt()?

texts:
I'm making an LED spectrum analyzer with an Arduino Due and my PC. The audio processing is done on the PC, and then sent to the Arduino. The exact data sent is a 'coordinate', or more specifically, a number representing a particular band, and another number representing the maximum amplitude of that band. There are 11 bands. Each coordinate has a x and a y value, separated by a comma, and then sent on a new line.

This is my code as of now:

void loop() {
  if (Serial.available()) {
    xCoord = Serial.parseInt();
    yCoord = Serial.parseInt();
    if (xCoord != 0) {
      int r, g, b;
      for (int i = 0; i < 8; i++) {
        int fromCoordToIndex = ((xCoord - 1) * 8) + i;
        //
        //do some calculations for the color
        //
        strip.setPixelColor(fromCoordToIndex, strip.Color(r, g, b));
        strip.show();
      }
    }
  }
}

The problem is parseInt seems to be very very slow (it's not the timeout issue, it's set to 1). From what I can see, it seems to be skipping some data, so every now and then a band gets missed out. The only way I can fix this is to insert a delay between each coordinate being sent. I found that 40 ms works ok, but remember there are 11 bands, so that means about half a second to refresh the whole board, which feels like a slide show...

I've tried inputting individual characters and then using toInt, I've tried parseInt obviously, I've tried native USB (it's a Due), and I've tried fiddling with baud rates. None seems to have had any effect.


texts: Accidentally plugged in Arduino Uno before installing software, now it's not recognized by Windows 10, only powered by usb port

texts:
Just got a new Arduino Uno, accidentally plugged it in before installing the IDE and windows installed its drivers and had it under ports as a generic device on COM3 (it wasn't named Arduino Uno on device manager).

When I installed the IDE, I couldn't upload sketches to the board because it wasn't recognized. So I uninstalled the device from device manager and also the IDE. I pressed the reset button on the Uno, restarted my PC, reinstalled the IDE, then plugged in the Uno. Since then however, the device isn't read by Windows at all; device manager doesn't show it anywhere, nor does it even refresh when plugged in.

I tried this restarting/reinstalling process multiple times, it's also not a cable issue because I checked for that as well. The power LED is still on, and the pin 13 LED is blinking, but the Arduino isn't being recognized.

I've also tried using the Hardware Install Wizard, but that gives me

  This Device Cannot Start (Code 10)

I've been trying to run this for a while now.


texts: Controlling Dynamixel Ax-12 With Arduino Mega

texts:
I want to controll two dynamixel ax-12 servos using a arduino mega and I don`t know the commands that I should send to them using Serial.

Could anyone help me with this?
(And please keep in mind that I don`t want any more hardware. Just arduino board)


texts:
I just bought a rfid scanner hz 1050 module at $5 to add to my project,in the module I see a lot of pins to male my connections.
Am getting stuck on the ones to use for arduino.
I will be glad to anyone who helps me out.Thank you.


texts:
I am using this code on a arduino nano and works fine.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);           // select the pins used on the LCD panel

#include <OBD2UART.h>

COBD obd;

void setup()
{

  // start communication with OBD-II UART adapter
  obd.begin();
  lcd.begin(16, 2);
  // initiate OBD-II connection until success
  while (!obd.init());
}

void loop()
{
  int value;
  obd.readPID(PID_RPM, value);
  int value2;
  obd.readPID(PID_COOLANT_TEMP, value2);
  lcd.setCursor(0,0);
  lcd.print("RPM = ");
  lcd.print(value);
  lcd.print("     ");
  lcd.setCursor(0,1);
  lcd.print("ECT = ");
  lcd.print(value2);
  lcd.print("     ");
    }

But if OBD is not connected, then it's get stuck in the setup.
What I want to do is to go over setup even if obd is not connected, and try connect to OBD meanwhile...something like display "Connecting..." on first row and count something on second...

Thank you in advance


texts: Problem Uploading to arduino nano (atmega 328p)

texts:
I am using Arduino 1.8.1 and arduino nano (mega 328p) and ftdi driver.
In device manager it seems no problem, because it is detected as COM99. But it says a problem while uploading to the board as picture given.
Please Helpp..


texts: Problem to convert rotary encoder output to angle

texts:
I'm using this incremental rotary encoder with a rotating disc.

Here is my system:

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

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

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

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

I tried the following example code from Arduino website:

#define encoder0PinA  2
#define encoder0PinB  4

volatile unsigned int encoder0Pos = 0;

void setup() {

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

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

}

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

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

  Serial.println (encoder0Pos, DEC);
}

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

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

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

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

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


texts: Attiny85: how to rotate the servo continuously with a press of a button?

texts:
I'm trying to use two Bluetooth commands in my code:
one is press off a button "1" the servo should do its routine without stop
second one press of the a button "2" servo should stop.

What am I getting with my code is button 1 pressed servo is executing the routine only once and then I need to press again. But I want the routine to loop until I'll stop it.

I'm adding here the code:

  #include <SoftSerial.h>
#include <TinyPinChange.h>
#include <SoftRcPulseOut.h>
#define SERVO_PIN         0

#define REFRESH_PERIOD_MS 4

#define NOW               1

int pos = 0;

SoftRcPulseOut myservo;

SoftSerial mySerial(2, 3); // RX, TX
void setup()
{
 // Open serial communications and wait for port to open:
  mySerial.begin(9600);
  pinMode(greenPin, OUTPUT);
  myservo.attach(SERVO_PIN);

}

void loop() // run over and over
{
  char c = mySerial.read();
  if(c == '1')  selfservo();
  if (c == '2') selfservo2();
}

ok the selfservo() is:

void selfservo()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(REFRESH_PERIOD_MS);        // waits 20ms for refresh period
    SoftRcPulseOut::refresh(NOW);    // generates the servo pulse Now
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(REFRESH_PERIOD_MS);        // waits 20ms for for refresh period
    SoftRcPulseOut::refresh(NOW);    // generates the servo pulse Now
  }
}

and selfservo2() is:

void selfservo2()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree

  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {

  }
}


texts: How could I port Arduino code to other embedded boards? For instance, I am working on a project using openPicus. I want to port the Arduino code to openPicus. How could I do this?


texts:
I recently bought an ESP-01 as well as an FTDI programmer (3.3v-5v) and after typing AT+GMR I noticed it said:

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

I have looked and looked on a way to upgrade its firmware (on MacOS) to no avail. How can I upgrade it? I want to be able to change the baud rate to 9600. A lot of examples to do it are in windows requiring another application or something like that but how can I do it in a Macbook? Thanks.


texts: I2C with an arduino, a PI and an IO expander

texts:
im working on a project which requires alo i/o pins. For that reason i bought a pcf8574P 8bit I/O expander which uses the I2C protocol. The problem is how to combine the Rasp PI and the arduino.
For example:
I want the Rasp to send data to the Arduino. Currently i'm using serial but i wanted to switch over to I2C because it better, simpler, and faster however how can i use 2 I2C when the Atmega 328P supports only 1 I2C bus?
The plan goes like this:
The PI is master of the arduino and it sends the data. Arduino is the slave
Arduino is master of the IO expander and the expander is slave
Possible solutions:

Use the Serial protocol to send the data and use the I2C for the expander
Make the arduino master of the PI and the expander which i'm not sure if its possible


texts: can i use L298N H bridge with 12v 7AH battery?

texts:
guys i am working on a rare project so i just need to ask some questions
I have a L298N H bridge motor driver, a Aduino uno board, 12v dc 4000rpm 2ampere motor and a 12v 7ah battery
I just want to ask can i use 12v 7ah battery with my L298N H bridge motor driver
please answer this project is very important to me
please help


texts:
void setup() {
  pinMode(13, OUTPUT);  // Red
  pinMode(14, OUTPUT);  // Yellow
  pinMode(15, OUTPUT);  // Green
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(14, LOW);
  digitalWrite(15, LOW);  // Stop
  delay(20000);           // Wait 20 seconds
  digitalWrite(13, HIGH);
  digitalWrite(14, HIGH);
  digitalWrite(15, LOW);  // Listen
  delay(20000);           // Wait 20 seconds
  digitalWrite(13, LOW);
  digitalWrite(14, LOW);
  digitalWrite(15, HIGH);  // Go
  delay(20000);            // Wait 20 seconds
}

How good is this code and is there any error ?


texts:
Pin 13 fires relay when powering on... How to disable?
I'm using pro mini 5v 16MHz and a DC 12V 2 Channel Relay Module Optocoupler. The relay Jd-VCC is powered by a 12V and it's VCC is 5V (the same as Arduino VCC). The relay is active low and I soldered pins 12 and 13 of the pro mini to IN1 and IN2 of the relay.

When I power the board up it cycles Pin 13(and the on-board LED) ON and then OFF before resuming to the code I uploaded. I believe that this can be fixed by disabling this blinking function in the startup process.

I understand that I can use other pins. Why not learn how to remove this from startup, if I prefer to use this pin for circuit layout purposes?

Any help would be much appreciated. Most of my searches ended up with people using the pin as an input... My issue is when using D13 as an active low pin it has some funky behavior at startup but then works as programmed.

Thanks!!!


texts: How to hook up an LED strip to an Arduino

texts: I want to add 6 LEDs  under my Arduino case and have the Arduino Uno pulsate the colors. How do I do this?


texts:
I would like to use OTA in some of my less accessible esp's. I am using the examples/BasicOTA and BasicOTA_test. My esp is a -01 model with 1Mb of flash.

I upload the BasicOTA to my esp through the COM port, then upload the BasicOTA_test over WiFi.  Everything appears to go OK, but the test sketch doesn't run until I press reset on the esp.

If I upload BasicOTA over the com port then upload a simple blink sketch over WiFi without the OTA code, it uploads fine then runs without a reset.  But then, I can't upload over WiFi anymore.

If I have to hit reset every time I upload a new sketch that contains the OTA code, then why bother?

Tips would be appreciated.


texts:
I'm trying to upload a huge sketch to my Uno R2. It's compiling just fine but it fails to upload at 94% of writing to flash...

The program is so large because of a big array of data in a separate .h file:

#include <avr/pgmspace.h>
const unsigned char PROGMEM data[] = {
  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x80, 0x7f, 0x80, 0x7f, 0x80, (etc...)

A test sketch with just 12 bytes of data uploads fine, so the problem is either with the size or some weird bug triggered by some of the data.

Unless i'm missing something, this should technically work.

Command:

    /home/hatagashira/.arduino-1.6.5/hardware/tools/avr/bin/avrdude -C/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build8921209068074674980.tmp/program.cpp.hex:i

Output:

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/hatagashira/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         Setting bit clk period        : 5.0
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 3.3
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: reading input file "/tmp/build8921209068074674980.tmp/program.cpp.hex"
avrdude: writing flash (30110 bytes):

Writing | ###############################################    | 94% 5.10savrdude: stk500_recv(): programmer is not responding


texts: How to detect Arduino serial port programmatically on different platforms?

texts:
I am trying to write a little program that needs to detect Arduino ports automatically. I have tried many methods but haven't found any reliable way.

I can see that the Arduino IDE can detect it, by showing /dev/cu.xyz (Arduino Uno) or COM6 (Arduino Uno) etc.

How could I detect if the device connected to the serial port is an Arduino or not? Preferably without pre-flashing the Arduino with specific firmware.

I found this Python version, which uses serial.tools.list_ports.comports() here,  but it didn't work when I tested it on Windows and MacOS.

The best I can get is by using go-serial's USBManufacturer, I can get 'Arduino (www.arduino.cc)'.

I also found this post, about the same question, but without any solution.


texts: ESP8266 crashing with blue LED always on and without the word "w_flash" on startup

texts:
When using Arduino SoftwareSerial with ESP8266, the blue led turns always on every time I reset the circuit by power. The only way to take the ESP working again is reflashing with the SDK 2.2.1, AT Firmware.

Have tested AMS1117 and LM317 as Power supply;
I'm using level converter 3V3 <-> 5V;
Have choosen different pins on Arduino for TX and RX;
No problem when using Hardware Serial pins with no SoftwareSerial;
My application works fine. The problem arises when I power off and power on and using SoftwareSerial.

Have noted a difference on the startup of ESP8266 after it gets stuck.
Here is the original startup (at 74880bps), ESP working normally
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2592, room 16
tail 0
chksum 0xf3
load 0x3ffe8000, len 764, room 8
tail 4
chksum 0x92
load 0x3ffe82fc, len 676, room 4
tail 0
chksum 0x22
csum 0x22

2nd boot version : 1.7(5d6f877)
SPI Speed : 40MHz
SPI Mode : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 251
freq trace enable 1
rf[112] : 03
rf[113] : 00
rf[114] : 01
w_flash <-- check the presence of this word

SDK ver: 2.2.1(6ab97e9) compiled @ Jun  7 2018 13:59:14
phy ver: 1136_0, pp ver: 10.2

⸮⸮j⸮l <-- here ESP is ready for AT commands at 115200bps. This is the word "ready" at 115200

Now, when the problem arises
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2592, room 16
tail 0
chksum 0xf3
load 0x3ffe8000, len 764, room 8
tail 4
chksum 0x92
load 0x3ffe82fc, len 676, room 4
tail 0
chksum 0x22
csum 0x22

2nd boot version : 1.7(5d6f877)
SPI Speed : 40MHz
SPI Mode : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 251
freq trace enable 1
rf[112] : 03
rf[113] : 00
rf[114] : 01

SDK ver: 2.2.1(6ab97e9) compiled @ Jun  7 2018 13:59:14
phy ver: 1136_0, pp ver: 10.2

Someone knows what w_flash means?
EDIT
I solve the problem by creating my own firmware with arduino IDE for ESP8266. Seens to be some type of bug in AT firmware, maybe! Now I can pass more tasks for ESP8266, saving arduino memory or even removing the need for an arduino board.
Thanks to everyone who helped =]


texts:
I am using MEGA 2560 with 1.8inch TFT screen.

I am trying to use input capture (shown in the code below) feature along with TFT display (1.8inch TFT display). Now when I individually test the input capture and LCD code, it works as expected(results observed on the serial port). But when I initialize the TFT library and then call InitTimer5(). the code gets stuck.

void setup() {
  Serial.begin(115200);
  DEBUG(1);
  digitalWrite(LCD_LED,HIGH);
  DEBUG(2);
  TFTscreen.begin();
  TFTscreen.setRotation(90);
  TFTscreen.background(0, 0, 0);
  //ICP configuarion setup
  DEBUG(3);
  InitTimer5();
  DEBUG("timer initialized");
  StartTimer5();
}

Where,

  #define DEBUG(x) Serial.println(x)

Is timer 5 also used by the TFT library??

typedef enum {
      CAPTURE_1,
      CAPTURE_2,
      WAIT
  } timer_state_t;

  volatile timer_state_t flag = WAIT;

  // J:This is a 16-bit timer, so these values will always fit into an unsigned int
  volatile unsigned int Capt1, Capt2, CaptOvr;

  // J:Mind as well make this unsigned and give it 2x range since it can never be negative.
  volatile unsigned long T5Ovs;
  unsigned char doubleOverflowError=0;

  void InitTimer5(void)
  {
     //Set Initial Timer value
     // J:All measurements against TCNT are relative, so no need to reset
     // TCNT1=0;

     // J: Note we need to set up all the timer control bits because we do not know what state they are in
     // J: If, for example, the WGM bits are set to a PWM mode then the TCNT is going to be resetting out from under us rather than monotonically counting up to MAX

     TCCR5A = 0x00;      //<---------The code gets stuck at this line

     //First capture on rising edge
     TCCR5B =(1<<ICES5);
     //Enable input capture and overflow interrupts
     //Timer interrupt mask register (Input capture intrrupt and overflow interrupt enable)
     TIMSK5|=(1<<ICIE5)|(1<<TOIE5);
  }

 // J: Note that it would be ok to start the timer when we assign TCCR1B in InitTimer since nothing will happen when the ISR is called until we set flag to CAPTURE1

  void StartTimer5(void)
  {
  //Start timer without prescaler

  // J: Note that we know that the other CS bits are 0 becuase of the Assignment in InitTimer
  TCCR5B |= (1<<CS50);

  //Enable global interrutps
  // J: Interrupts are turned on by  Arduino platform startup code
  //  sei();
  }

  ISR(TIMER5_CAPT_vect) {

   switch(flag) {
   case CAPTURE_1:
       Capt1 = ICR5;

       // J: Reset the overflow to 0 each time we start a measurement
       T5Ovs=0;
       doubleOverflowError=0;
       flag = CAPTURE_2;
       break;

   case CAPTURE_2:
       Capt2 = ICR5;

       // J: Grab a snap shot of the overflow count since the timer will keep counting (and overflowing);
       CaptOvr = T5Ovs;
       flag = WAIT;

       //J: Generally bad to print in ISRs
       //Serial.println(flag);

       break;
      }
  }

  ISR(TIMER5_OVF_vect)
  {
    T5Ovs++;

    // J: Just to be correct, check for overflow of the overflow, otherwise if it overflows we would get an incorrect answer.
    if (!T5Ovs) {
      doubleOverflowError=1;
    }
  }
unsigned long sensor_freq()
  {
    unsigned long count=0;
    unsigned long frequency=0;

    // J: No need to bracket this set with cli() becuase the counter will not be counting until wait is updated

    flag = CAPTURE_1;

    while (flag != WAIT); //Need to figure way to eliminate this wait time.

    // J: Parenthesis and explicit cast for good luck! ( and to ensure correct size and order for operations)

    count=( (unsigned long) (Capt2) + (CaptOvr * 0x10000UL) )-Capt1;

    frequency= 0.0625*count;       //16Mhz ^-1 = 0.0625 e-6
    frequency=1000000/frequency;

   return(frequency);
}


texts: HD44780 DDRAM addressing on the second line

texts:
I write bytes to HD44780 display DDRAM to display characters and it works weird on the second line. I use 16x2 model and I write "0123456789" string from address X on.

According to the datasheet:

  In a 2-line display, the cursor moves to the second line when it passes the 40th digit of the first line.

So when I set X to 40, the string appears from the beginning of the second line. So far so good. But when I change X to different values, this appears on the second line:

X=39 ... 123456789
X=40 ... 0123456789
X=41 ... 0123456789
...
X=47 ... 0123456789
X=48 ... 89
X=49 ... 789
...
X=56 ... 0123456789
X=57 ... 0123456789
...
X=64 ... 0123456789
X=65 ...  0123456789
X=66 ...   0123456789

Since address X=64 it works as expected, so increasing X by one shifts the string to the right by 1 character. The datasheet also says

  However, when N is 0 (1-line display), AAAAAAA can be 00H to 4FH (79). When N is 1 (2-line display),
  AAAAAAA can be 00H to 27H (39) for the first line, and 40H (64) to 67H (103) for the second line.

So the second line starts at 40H (64), not 40, it seems. Is it a confusion? What is the idea between address 40-64? It would make sense if the second line was address 28H-40H. I don't see the explanation in the datasheet. Also, how the DDRAM works for 20 characters per line and 4 lines displays?


texts: Can I mix 22awg and 26awg hookup wire in the same circuit?

texts: I'm still fairly new to Arduino projects, and am only just now getting into building circuits where I want to cut and place my own hookup wire instead of using the precut jumper wires. I inherited some supplies from a friend who abandoned the hobby, and about half of the wire he gave me is 22awg and the other half is 26awg. All of it is solid core copper. Is it ok to mix wire gauges like this in the same circuit/project?


texts: How can I get an integer from an RFID tag from Arduino Mega to NodeMCU 1.0 over serial communication?

texts:
I want the number from an RFID tag read by a reader connected to an Arduino Mega to end up as a string on a NodeMCU connected to the Mega. I am trying to confirm that the string is on the NodeMCU using the serial monitor. With the code below, the serial monitor for the NodeMCU prints "receivedChars:" only and not the number from the tag. What am I missing?
Code for Arduino Mega

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

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

String sent = "n";
String UID_string = "";

void setup() {

    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
    Serial.begin(115200); // Initialize serial communications with the PC
    Serial.println("Running Version Jan5a");
    Serial.println("Mega:Serial Monitor initialized at 115200 baud...");
    Serial3.begin(9600); // Initialize serial communication with ESP
    Serial.println("Mega:Serial Port 3 for NodeMCU initialized at 9600 baud...");
    Serial.println("Mega: Scan PICC to see UID and type...");
}

////////

void SendUIDtoESP() {

if (sent == "n") {
  Serial.print("sent= ");
  Serial.print(sent);
  //if (UID_string.length() > 0)  {
  UID_string = "Hello World"; //test line
  Serial3.print("<");
  Serial3.print(String(UID_string));
  Serial3.print(">");
  Serial.println("Mega:Sending UID string to ESP");
  sent = "y";
  Serial.print("after sending, sent= ");
  Serial.print(sent);
//  } else {
 //   Serial.println("Mega: Error: UID-string not set yet!");
  //}

}
} // end Send UID to ESP

void loop {
SendUIDtoESP() ;
}

Code for NodeMCU

int numChars = 0;
String receivedChars = "";
boolean newData = false;
String tag = "";
unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

SoftwareSerial s(D1,D2);// assign pins to send data to and receive data from NodeMCU to Arduino Mega rx, tx

void setup() {
Serial.begin(9600);
    s.begin(9600);
    Serial.println("NodeMCU: Waiting for serial connection with Mega to be available over s");
  while (! s.available() >0){
    Serial.print("."); // waiting
    return;
  }
  Serial.println("NodeMCU: Looks like Mega is available.");
} // end void setup

 void recvWithStartEndMarkers() { //listen to Mega
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

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

        if (recvInProgress == true) {
            if (rc != endMarker) {
                Serial.println(rc);
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }
        else if (rc == startMarker) {
          Serial.println("startMarker received");
            recvInProgress = true;
        }
    }
} // end recvWithStartEndMarkers()

void loop() {
recvWithStartEndMarkers();
}


texts: writing and uploading sketch as cpp file

texts:
I want to use only *.cpp files and no *.ino anymore. I read a lot of stuff about how to upload c++ instead of arduino sketches. But still I was not able to find a step by step guide how to do it.

Actually I am developing my sketch within Spacemacs (Emacs) and uploading it with Arduino-Makefile (https://github.com/sudar/Arduino-Makefile)

When I now want to start a new project with only *.cpp and *.h files to use classes etc. how would I start? Does anybody has the time to describe a rough step-by-step without the trivial stuff?


texts: How to read two byte register address using arduino wire library

texts: I want to read a register 0x012A from the device I2C address 0x0A, the value stored in the register is two bytes, If the register address is one byte i can use Wire.requestFrom and give the register address and how many bytes i want to read since here register address itself 2 bytes i'am bit confused . can any one help in this regard.


texts: Using Arduino fix_fft or arduinoFFT library to filter some specific sound?

texts: I would like to know if there is a way to filter some specific sound using FFT on arduino. For instance, there is wind sound frequency in my analysis and I want to take it off. I searched for that a lot, but I didn't find something useful to solve this problem.


texts: 27 Servo Project, Uno with Adafruit's 16-Channel Drivers

texts:
I'm working on a project where I need to be able to control 27+ servos. The problem is that I am unsure how to control them from a computer. I'd love to build a simple program with a user interface that I could select each individual servo, and it would rotate a fixed amount and back to the starting setting. Does something like this exist? I've found a number of little projects that have some form of GUI, though I can't find enough information on any of them. Can anyone recommend where I start?
Thank you!

-L


texts: Problems with AccelStepper/Multistepper library

texts:
I am trying to drive two stepper motors with the AccelStepper/MultiStepper library. I think I did get it to work before, but it's not working now. I have included my code below the error messages.
Is there something wrong with the code I have written or is there something within the library that I need to change?
    C:\Users\Shreeya\AppData\Local\Temp\ccTKlUO9.ltrans0.ltrans.o: In function `AccelStepper::enableOutputs()':

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:560: undefined reference to `pinMode'

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:561: undefined reference to `pinMode'

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:564: undefined reference to `pinMode'

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:569: undefined reference to `pinMode'

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:574: undefined reference to `pinMode'

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:575: undefined reference to `digitalWrite'

    C:\Users\Shreeya\AppData\Local\Temp\ccTKlUO9.ltrans0.ltrans.o: In function `AccelStepper::disableOutputs()':

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:550: undefined reference to `pinMode'

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:551: undefined reference to `digitalWrite'

    C:\Users\Shreeya\AppData\Local\Temp\ccTKlUO9.ltrans0.ltrans.o: In function `AccelStepper::setOutputPins(unsigned char)':

    C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper\src/AccelStepper.cpp:366: undefined reference to `digitalWrite'

    c:/program files/windowsapps/arduinollc.arduinoide_1.8.42.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/7.3.0/../../../../avr/lib/avr5/crtatmega328p.o:(.init9+0x0): undefined reference to `main'

    collect2.exe: error: ld returned 1 exit status

    Using library AccelStepper at version 1.61 in folder: C:\Users\Shreeya\Documents\Arduino\libraries\AccelStepper

    exit status 1

    Error compiling for board Arduino Uno.

Main code:
#include <AccelStepper.h>
#include <MultiStepper.h>

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

// Define motor interface type
#define motorInterfaceType 1

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

MultiStepper steppers;

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

void loop() {
  long positions[2]; // Array of desired stepper positions

  positions[0] = 1000;
  positions[1] = 500;
  steppers.moveTo(positions);
  steppers.runSpeedToPosition(); // Blocks until all are in position
  delay(1000);

  // Move to a different coordinate
  positions[0] = -1000;
  positions[1] = 1000;
  steppers.moveTo(positions);
  steppers.runSpeedToPosition(); // Blocks until all are in position
  delay(1000);
}


texts: Light LED when 2 others are disconnected

texts:
I need to make circuit in which orange LED will light only when yellow and red are disconnected. When one of buttons is pushed orange LED should turn off.

See my attempt at it below.

I am new to electronics so your help is very appreciated.

EDIT:

After many atemps I managed to build this circuit as on left side of schematic (tested on live breadboard)

but my primary goal is to make this work with RGB LED. I took Common Anode RGB LED for this and build circuit on right side of schematic. I do not have such RGB LED to test it live so I ask you to review if that schematic will work as it has few changes to one with 3 LED's. Thank you

SOLUTION:

Thanks to Bruce's help my circuit now works.

3 separate LEDs emulate common anode RGB LED (as I do not have one to test circuit)
Q2 is BC 560B transistor with CBE type pinout

CODE:

void setup() {
  pinMode(2,INPUT);
  pinMode(4,INPUT);
  Serial.begin(9600);
  digitalWrite(2,HIGH);
  digitalWrite(4,HIGH);
}

void loop() {
  Serial.println(digitalRead(2));
  Serial.println(digitalRead(4));
}


texts: Verifying the timing between relay activations

texts:
I would like to verify timings of a relay controlled by an arduino (uno R3). There is a lot going on in the sketch and it does not use the delay function but one which is based on counting milliseconds. The arduino then transmits to another arduino using a radio module (nRF24L01). I'd like to confirm the intervals between the relay, so for instance if the relay is acivated 10 times and there are 5 seconds between each actvation.

So what I was wondering was whether anyone had any reccomendations on methods to verify timings using an external source.

Two ideas I came up with were: have another arduino with a very simple script that measures the timings or try and find/write a verilog script to upload to a mojo fpga and measures the timings.

An ideal situation would be where I have a seperate device that hooks up to the relay and then measures and displays the timings between the relay switches and is extremely precise.

I hope that makes sense, if not please let me know and I'll explain further. Thank you for reading and any help is greatly appriciated.


texts:
I'm very new to Arduino, and I was wanting to control my Arduino wirelessly. Some googling shows that there is a shield for Arduino called Xbee that allows wireless communication. Unfortunately, I just purchased the #1 shield without checking specifications, (went back later, couldn't find them :/) and now i have a shield that appears to small for my Uno. (XBee Pro 60mW Wire Antenna - Series 1 (802.15.4))

Some more googling showed results that this was indeed the right shield, but I don't see how since the pin pattern is about half the size as the female ports on the Arduino. Is this the right shield? if so, how do I attach the two pieces of hardware?


texts: Convert normal keyboard into Bluetooth Keyboard

texts:
I am very new to the Arduino world, I am trying to convert my wired keyboard into a bluetooth keyboard. I have a few layman questions:

Is it possible to add an audio jack adapter(like PS4 joystick has), so that I can plugin my headphones to my keyboard itself to listen to the music.
Is it possible to achieve this(bluetooth keyboard + audio jack) on Arduino or do I need to use Rasberry-pi?
Is there a way to keep my current USB wire? so that I can keep working even if the battery runs out.
I want to keep all the apparatus in the keyboard casing itself, can you please suggest smallest Arduino board that will work for my use case.
I am not sure if I need a special kind of bluetooth breakout board for this(that can receive audio as input and send keystrokes to my system). Can you please guide what will be the best fit board.

Thanks in advance.


texts: Why can't I use 3V output of arduino pro mini?

texts:
I have an Arduino pro mini and I tested digital write of an pin and it is 3.2V and then I connected it to a 3V motor, but when I connected the motor to it, The voltage drops under 0.2 Volt, Can any one describe the science behind voltage drop ?

I know I've better use a transistor and separate the motor power but, what you should do when you have a single 3V power source? and I know there are some motor driver chips, but is it possible to keep it simple?