texts:
I've connected SD card module to Arduino UNO. I want to use PIN 10 for PWM DC motor control and because of that, I've connected CS pin directly to another pin (A3).

SD card is working properly, but after calling SD.begin(A3), it set PIN 10 to HIGH!
Immediately after SD.begin(A3) and set that pin to LOW, but meanwhile the motor took a small rotation.

I've digged into SD.cpp and Sd2Card.cpp, but couldn't find where this problem occured!

Any help appreciated....

The Solution:
Simply call SD.begin(-1) and it doesn't touch PIN10. Hope helps somebody else!


texts: Can I power a 9g servo from an arduino nano with USB power only?

texts:
I want to run a 9g servo off of the pins from an arduino nano board, using only the 5v USB connection.

The servo specifically is a SG90, which I have measured a stall current of ~250mA - I don't intend to stall it, just have it run with almost no load

I am not sure which pins to power it off of from the arduino itself - do I use the VCC or the +5v? does it matter which ground I use? should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something? does the arduino nano negotiate to get more than the default of 100mA from a USB power connection?


texts: Adafruit TLC5947 breakout board is not working with my Arduino Uno

texts:
I am trying to use this board (setup tutorial on left hand nav) with my Arduino Uno.  I have tried using their example code, as well as my own simplified code, to turn on a single blue LED.

The simplified code I "wrote" is as follows:

#include "Adafruit_TLC5947.h"

#define NUM_TLC5974 1

#define data   3
#define clock   5
#define latch   6

Adafruit_TLC5947 tlc = Adafruit_TLC5947(NUM_TLC5974, clock, data, latch);

void setup() {
  tlc.begin();
}

void loop() {
  tlc.setPWM(0, 4095);
  tlc.write();
}

  Scroll to the bottom for reference. (TLC5947)

This compiles and uploads successfully.  I have DIN connected to 3, CLK to 5, and LAT to 6.  V+ is connected to the Arduino 5V pin, and GND to Arduino ground.

Using this setup, the LED does not turn on when connected to channel 0 on the board.  Using a multimeter, I have verified that the voltage between common ground and the channel 0 pin is ~0V.  Checking voltage on the board between GND and V+, I see 4.8V, which looks good.  Connecting the LED directly to the V+ line lights it up, but obviously isn't switchable.

I have no clue why I'm not seeing anything on channel 0's output when I directly write it to 100% duty cycle.

Why is this not working?


texts: Ultrasonic Sensor(HC-SR04) recording random distance

texts:
I am am trying to make a code which automatically controls relay on basis of ultrasonic sensor measurements. I am using a nodeMCU as a microcontroller rather than an arduino. The relay and the ultrasonic sensor is being powered from a 5V source and nodemcu from a 3.3V Source. I don't think none of the sensors are interfering with each other as all the sensors are kept at a distance. Due to the random values my relay is being latched without any reason.
Can someone please help me out with the problem. I don't want these values(above 3000) being shown in the serial monitor.
#define TRIGGER 5
#define ECHO    4
#define RELAY   0

void setup() {
  Serial.begin(9600);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
  pinMode(RELAY, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  }else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}


texts:
I was designing a circuit that measure distance using HC-SR04 and display it into a LCD.This circuit also have 4 LEDs indicator.But i have a problem.The LEDs doesn't turn on.The LCDs backlight turn on, but it didnt display anything. Btw, i'm using LCD with I2C module.Here is the code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#define trigPin 6
#define echoPin 7
int led5cm = 8;
int led7cm = 9;
int led10cm = 10;
int ledoor = 11; //ledoor means LED Out of Range
void setup() { // put your setup code here, to run once: lcd.begin(16,2); lcd.setCursor(0,0);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led5cm, OUTPUT);
  pinMode(led7cm, OUTPUT);
  pinMode(led10cm, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  if (distance <= 5)
  { lcd.println("Distance < 5 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, HIGH);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  } else if (distance >= 5 || distance <= 7) {
    lcd.println("Distance < 7 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, HIGH);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance >= 7 || distance <= 10) {
    lcd.println("Distance < 10 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, HIGH);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance > 10) {
    lcd.println("Out of Range");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
}

Can you please help me solve this problem? Thank you very much!!


texts: How can I use the NRF24L01 modules without a library?

texts: The datasheet is too intimidating for me, and I dont want to use the libraries available. Hence, I am looking for some clarity on this matter.


texts:
I'm currently sending around 30 sensor values from one arduino to another with a radio frequency module. I serial print the data with commas so that I can easily plot the results after a test.
However, I'd like to create formal data packets that can be checked for errors and validated on the fly. I've done a lot of googling but I haven't found any resources that explain how to create your own.
Furthermore, is there any protocol that you would recommend over another. How would one go about selecting a protocol?
Thank you.


texts: How to reset the count/data after HTTP.POST?

texts:
I have a project that records interrupts from a reed switch to nodemcu.
It records like this: 0.3,0.6,0.9,1.2 Then what I want to happen is to go back to zero when it successfully HTTP.POST to a webserver.
How can I do it? Thanks!
volatile float rainrate = 0.3;
volatile float total;

void count {
  total += rainrate;
}


texts: Interfacing Arduino Leonardo with PCA8574AN

texts:
I'm trying to interface my Leonardo with a "Mindsensors Magic Wand" - 8 LEDs connected to a PCA8574AN chip.
On the manufacturer's page, they say it's compatible with Arduino, however no instructions or code are given.
http://www.mindsensors.com/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=120

I've connected the SDA, SCL, 5v, and GND connectors on the arduino to the device, but have had no luck in communicating with it. None of the LEDs light up regardless of input.

I can verify that power is being supplied.
The i2c address of the device is 0x70.
Code is below.

#include "Wire.h"
#define TWBR=400000L
void setup() {
  // put your setup code here, to run once:
 Wire.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
  Wire.beginTransmission(0x70);
  Wire.write(32);
  Wire.endTransmission();
}


texts: ESP32 preferences library: casting byte array back to struct

texts:
I'm new to both C and the Arduino framework and having difficulty fully understanding casts.  Using this code as an example, I'm attempting to store a struct locally into flash. Code for two functions listed below.  I am successfully writing to, and reading from preferences, however I don't yet have a full grasp on what's happening.
#define SSID_LENGTH 10
#define PASSWORD_LENGTH 16

struct netcfg{
  char ssid[SSID_LENGTH];
  char password[PASSWORD_LENGTH];
};

netcfg read_netcfg(const char* prefNamespace) {
    Serial.println("Reading Config");
    Preferences pref;
    pref.begin(prefNamespace, false);
    size_t conf_size = pref.getBytesLength(prefNamespace);
    Serial.printf("Size of %s namespace is %d bytes\n", prefNamespace, conf_size);
    byte buffer[conf_size]; // prepare a buffer for the data
    pref.getBytes(prefNamespace, buffer, conf_size);
    for(int x = 0; x<=conf_size; x++){
      Serial.print(buffer[x]);
      Serial.print(' ');
    }

    netcfg *cfg = (netcfg*) buffer;
    Serial.printf("\nssid: %s \npassword: %s", cfg[0].ssid, cfg[0].password);
    return *cfg;

void write_netcfg(const char* prefNamespace, netcfg cfg) {
  Serial.println("Writing Config");
  Serial.printf("netcfg size: %3d", (int) sizeof(netcfg));
  Preferences pref;
  pref.begin(prefNamespace, false);
  pref.putBytes(prefNamespace, &cfg, sizeof(netcfg));
}

My quandary is specifically with this particular line:
netcfg *cfg = (netcfg*) buffer;

I'm trying to determine how this works. I'm creating a pointer named cfg, which will reference data of the netcfg struct.  That is being initialized to the buffer byte array.  The problem is that this does not compile if I attempt to change this to an individual struct as follows:
netcfg *cfg = (netcfg) buffer;

When compiling, I get the following error:

error: no matching function for call to 'netcfg::netcfg(byte [conf_size])'

Can you help me understand the technical reasoning behind the first cast working, and how I can avoid the use of the array?
Thank you!


texts: Serial doesent work when calling function from timer

texts:
You can try the code on your arduino UNO to better understand what is hapening in serial monitor!
I want to calculate jacobian matrix from rotation matrix!
float jakMATB[3][3] = {
{0, 0, 0},
{0, 0, 0},
{0, 0, 0}
     };
float POKUS = 0;
float k = 0.000001;
float dt = 0.001;
float b = 90 * (PI / 180);
float vnB[3] = {0, 1, 0}, vpB[3] = {0, 1, 1};
float nB[3] = {0, 1, 0};
float nBplus[3] = {0 , 1, 0};
float nBminus[3] = {0, 1, 0};
void setup() {
Serial.begin(9600);
Serial.print("init ok");
cli();//stop interrupts
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1  = 0;//initialize counter value to 0
// set compare match register for 1hz increments
OCR1A = (16000000) / ((1 / dt) * 1024) - 1; // 15624 = (16*10^6) / ((1)*1024) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12 and CS10 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();//allow interrupts
}

when I call the function in loop everithing works fine and I get  1 2 1 in serial monitor
 void loop() {
 izracunJAKOB();
 for (int j = 0; j <= 2; j++) {
for (int i = 0; i <= 2; i++) {
  Serial.print(jakMATB[j][i]);
  Serial.print(" ");
}
Serial.println("");
}
}

when I call izracunJAKOB() with timer interupt Serial monitor
stops working and doesent event write "init ok"
ISR(TIMER1_COMPA_vect) {
  //izracunJAKOB();
 }
void izracunJAKOB() {
for (int j = 0; j <= 2; j++) {
for (int i = 0; i <= 2; i++) {
  nBplus[j] = nB[j] + k;
  nBminus[j] = nB[j] - k;
  float matricaBplus[3][3] = {
    {cos(b) + nBplus[0]*nBplus[0]*(1 - cos(b)), nBplus[1]*nBplus[0]*(1 - cos(b)) - nBplus[2]*sin(b), nBplus[0]*nBplus[2]*(1 - cos(b)) + nBplus[1]*sin(b)},
    {nBplus[1]*nBplus[0]*(1 - cos(b)) + nBplus[2]*sin(b), cos(b) + nBplus[1]*nBplus[1]*(1 - cos(b)), nBplus[1]*nBplus[2]*(1 - cos(b)) - nBplus[0]*sin(b)},
    {nBplus[0]*nBplus[2]*(1 - cos(b)) - nBplus[1]*sin(b), nBplus[1]*nBplus[2]*(1 - cos(b)) + nBplus[0]*sin(b), nBplus[2]*nBplus[2]*(1 - cos(b)) + cos(b)}
  };
  float matricaBminus[3][3] = {
    {cos(b) + nBminus[0]*nBminus[0]*(1 - cos(b)), nBminus[1]*nBminus[0]*(1 - cos(b)) - nBminus[2]*sin(b), nBminus[0]*nBminus[2]*(1 - cos(b)) + nBminus[1]*sin(b)},
    {nBminus[1]*nBminus[0]*(1 - cos(b)) + nBminus[2]*sin(b), cos(b) + nBminus[1]*nBminus[1]*(1 - cos(b)), nBminus[1]*nBminus[2]*(1 - cos(b)) - nBminus[0]*sin(b)},
    {nBminus[0]*nBminus[2]*(1 - cos(b)) - nBminus[1]*sin(b), nBminus[1]*nBminus[2]*(1 - cos(b)) + nBminus[0]*sin(b), nBminus[2]*nBminus[2]*(1 - cos(b)) + cos(b)}
  };
  jakMATB[i][j] = (matricaBplus[i][j] - matricaBminus[i][j]) / (2 * k);
  nBplus[0] = 0;
  nBplus[1] = 1;
  nBplus[2] = 0;
  nBminus[0] = 0;
  nBminus[1] = 1;
  nBminus[2] = 0;
}
}
}

//////////////////////////////
when I comennt out
   nBplus[j] = nB[j] + k;
   nBminus[j] = nB[j] - k;

and
   nBplus[0] = 0;
   nBplus[1] = 1;
   nBplus[2] = 0;
   nBminus[0] = 0;
   nBminus[1] = 1;
   nBminus[2] = 0;

Serial works just fine
when I coment out only  matricaBminus and  matricaBplus serial works fine
Please help! It surely is a stupid solution!


texts: Multiple I2C slave devices on Arduino - Pull-up values

texts:
This question is asked a lot and I've found many usable details on different forums regarding adding pull-up resistors on SDA/SCL lines. I know that only one resistor should be added on these lines regardless of how many devices are attached.

One thing that is not clear for me is that what if I2C devices are powered on from different sources, at different timing?
In following schematic, I have used pull up resistors for both I2C devices. Considering devices might be turned on and off at different timing, or even one device might be absent, is it fine to remove the second pull up resistors (second I2C device) and connect them directly to SDA/SCL pins on uC? In this case (removing pull-up resistors from second device), what happens if device 1 is not available and only second device is connected?

---edit:

Schematic was updated to include only one pair of pull up resistors connected to master side.
I will not how swap or hot plug I2C devices.
I2C devices are sensors (BME280 here, and Chirp capacitive soil moisture, here), not on breakout boards with preset pull up resistors.
Is it possible to just connect resistors on master side and not slave side? In this case, would it be fine for both sensors?

simulate this circuit – Schematic created using CircuitLab


texts: DC Motor fan control with Temperature sensor

texts: I used TinkerCAD circuit for the project however, when DC Motor starts to work, temperature value is increasing abnormally high. How can I solve this problem? Link for the tinkercad:


texts: Which board to select in PlatformIO for ESP Wroom 32?

texts:
I'm quite new in this microcontroller topic and my next step is to make use of a wlan module, which is a ESP WROOM 32.
As IDE I'm using Visual Studio + PlatformIO and I can't figure out how to access the module. Atm I use these parameters:
[env:esp12e]
platform = espressif8266
board = esp12e
framework = arduino
monitor_speed = 74880

but I receive:
(...)
CURRENT: upload_protocol = esptool
Looking for upload port...
Auto-detected: /dev/ttyUSB0
Uploading .pio/build/esp12e/firmware.bin
esptool.py v2.8
Serial port /dev/ttyUSB0
Connecting......
Chip is ESP8266EX
Features: WiFi
WARNING: Detected crystal freq 20.45MHz is quite different to normalized freq 26MHz. Unsupported crystal in use?
Crystal is 26MHz
MAC: 00:08:ff:00:00:00
Uploading stub...
Running stub...

A fatal error occurred: Invalid head of packet (0x46)
*** [upload] Error 2
============================================================================= [FAILED] Took 3.27 seconds =============================================================================
The terminal process "platformio 'run', '--target', 'upload'" terminated with exit code: 1.

edit:
The ESP WROOM 32 is a NodeMCU 32 and the board config now is:
[env:espwroom32]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200

and to check if everything works:
void setup() {
  pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(2, HIGH);
  delay(1000);
  digitalWrite(2, LOW);
  delay(1000);
}

I also had problems that I received Failed to connect to ESP32: Timed out waiting for packet header nevertheless but here is a nicely explained workaround for that. Solution is, either you hold the BOOT button pressed while uploading the code or you sold a capacitor to specific pins on the board.
I just tried to hold the boot button and it's blinking now. Finally :)
I'm sure, a lot of further issues are only waiting on the way ^


texts: Maximum power rating for Arduino UNO revision 2 (SMD)

texts:
I have located the 5V voltage regulator chip on my Arduino board which I am hoping to use to power an attached device (which draws up to 500 mA at 5V).  The chip is next to the plug for the external voltage supply.  It says: ON RUX 117-5.  It looks like it's in a SOT−223 package (body about 6.1 by 3.4mm).

I used this page to shows 3 different possible voltage regulators from ON Semiconductors: https://www.mouser.co.uk/ON-Semiconductor/Semiconductors/Power-Management-ICs/Voltage-Regulators-Voltage-Controllers/LDO-Voltage-Regulators/_/N-5cgac?P=1z0wa29Z1z0xwtvZ1z0zlrjZ1ywvc7yZ1yxz1yoZ1ywvc5z

This gives two unique data sheets for NCP1117LP and NCP1117, NCV1117.  But this is where I'm stuck.  They look pretty similar but not exactly the same data sheets.  Also I don't know what RUX stands for, perhaps this is important in figuring out what power rating the Arduino 5V line has.
Additionally the mouser.co.uk site says they're in SOT-223-3 packages but then gives dimensions which a) aren't the dimensions of the chip I have and b) are the dimensions of the SOT-223-4 package (6.3mm wide instead of the ~6.1 mm I have).

I don't care about the dimensions but I would like to correctly identify the chip on the Arduino board to be able to know what power I can draw from it before it shuts itself down.


texts: Strange phenomenon when declaring double

texts:
Consider this question closed, found my answer through the answers I had

I am trying to make a position profile curve depending on Looptime, accelerationloops,Setposition,Currentposition(position) and velocity.
The curve should look like this:

Is someone able to check what is wrong with my code?

float array[30];

struct Formula {
  int LoopTime = 1000;
  int AccelerationLoops = 11;
  float VelocityLoop = 0;
  float VelocityFactor = 0;
  int TotalLoops = 0;
  float DeltaPosition = 0;
  int Setpoint = 0;
  int Iteration = -1;
  float EndOne = 1.25;
}Formula;

float SetPosition = 1404;
float Position = 0;
float Velocity = 36;

void setup() {
  Serial.begin(115200);
  for(Formula.Iteration ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    ProgFormula();
    Serial.println(Formula.Iteration);
    if(Formula.Iteration >= 0) {array[Formula.Iteration] = Formula.Setpoint;}
  }
  for(Formula.Iteration = 0 ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    //Serial.println(array[Formula.Iteration]);
  }
}

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

}

void ProgFormula(){
  if(Formula.Iteration == -1) {
    Formula.DeltaPosition = SetPosition - Position;
    Formula.VelocityLoop = Velocity / (1000 / Formula.LoopTime);
    Formula.TotalLoops = Formula.DeltaPosition / Formula.VelocityLoop + Formula.AccelerationLoops;
    Formula.VelocityFactor = Formula.VelocityLoop * 0.5 / Formula.AccelerationLoops;
    Formula.EndOne = (Formula.VelocityFactor*pow(Formula.AccelerationLoops,2));
  }
  else if (Formula.Iteration >= 0 && Formula.Iteration <= Formula.AccelerationLoops) {
    Formula.Setpoint = Formula.VelocityFactor * pow(Formula.Iteration,2);
  }
  else if (Formula.Iteration > Formula.AccelerationLoops && Formula.Iteration <= (Formula.TotalLoops - Formula.AccelerationLoops)) {
    Formula.Setpoint = Formula.VelocityLoop * Formula.Iteration - Formula.EndOne;
  }
  else if (Formula.Iteration >= (Formula.TotalLoops - Formula.AccelerationLoops) && Formula.Iteration <= Formula.TotalLoops) {
    Formula.Setpoint = -Formula.VelocityFactor * pow((Formula.TotalLoops - Formula.Iteration),2) + Formula.DeltaPosition;
  }
  else {
    Formula.Setpoint = Formula.Setpoint;
  }
}


texts: Activating a defined macro in a class from main.cpp

texts:
Sorry if this question been asked. I'm trying to activate certain function in a class using a macro defined in the class from main.cpp. I'm using jrowberg MPU6050 library if that matters.

main.cpp

#include "gyro.h"
gyro gyro(Serial);
#define OUTPUT_READABLE_EULER

void setup(){
...
}
void loop(){
...
}

gyro.cpp

  #include "gyro.h"
  #ifdef OUTPUT_READABLE_EULER
      // display Euler angles in degrees
      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetEuler(euler, &q);
      serial_.print("euler\t");
      serial_.print(euler[0] * 180/M_PI);
      serial_.print("\t");
      serial_.print(euler[1] * 180/M_PI);
      serial_.print("\t");
      serial_.println(euler[2] * 180/M_PI);
  #endif

If I define OUTPUT_READABLE_EULER in gyro.h, it works. But I want to do it from main.cpp.


texts: Is it possible to use the Arduino Due's specials pins for digital writing and reading?

texts:
Hello the arduino documentation on the due specifies the pin mapping of the pins.I am making a custom board using the dues schematics and i am running still a bit low on pins. Also some of the special pins offer a better position for traces.

So is it possible digitalWrite()/digitalRead() the specials pins such as:

RX (0-3)
TX (0-3)
SDA (0-1)
SCL (0-1)
CANRX
CANTX
LED RX
LED TX
MISO
MOSI
SCLK

As for the SPI and i2c lines i will be using them for the original purpose,but i would like to take the opportunity to know anyway.

I do not own a due so unfortunately i can not test it


texts: Programmed device causes issues between computer and ISP

texts:
I'm using a Digispark, which is basically an attiny85 packaged with a few other things, as an ISP to program attiny85's. The Digispark is loaded with Littlewire and recognized as an USBtinySPI device on the computer. The target attiny85 to be programmed is stacked on top of the Digispark. All pins are connected 1-to-1, 2-to-2, etc. Programming is done from the Arduino IDE. The tutorial I followed can be found here...

http://digistump.com/wiki/digispark/tutorials/programming

The Digispark uses port 3 (USB-) and port 4 (USB+) to communicate with the computer. There are series resistors and shunt zener diodes on both USB connections. The Digispark schematic can be seen here...

https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf

I have been happily programming attiny85's with this setup, but recently hit a snag. On the target chip, if port 3 or 4 produce an output, the computer will no longer recognize the programmer. The computer will immediately connect to the programmer once the target chip is removed from it's socket. The target chip must be messing up communication between the computer and the programmer.

Curious if I was missing something, I compared my setup with Sparkfun's Tiny AVR Programmer. It seems like a more robust programmer. I thought it might have extra components or something, but it's almost identical. It uses an attiny84 with pins directly connected to an attiny85.

After lots of random guesses, I added series 2.2kohm resistors on ports 3 and 4 between the target attiny85 and the programmer. This solves the problem, but seems like a workaround.

Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?


texts:
I need to add some end stops to this stepper motor code. I'm using one axis of a joystick to control a carriage that goes back and forth on a long screw. I have hall switches for both ends, I just want it to stop going in that direction when it triggers the switch.
I didn't write this code but it would work great if I could just add the end stops. If I have the switches connected to pins 2 and 3.
How could I write something like: if pin 2 goes high, stop motor in that direction, and then the same for pin 3 in the opposite direction?
#include <AccelStepper.h> // accelstepper library
AccelStepper stepper(1, 8, 9); // direction Digital 9 (CCW), pulses Digital 8 (CLK)

//Pins
const byte Analog_X_pin = A0; // x-axis readings
const byte enablePin = 7;

//Variables
int Analog_X = 0;             //x-axis value
int Analog_X_AVG = 0;         //x-axis value average
  //----------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  //----------------------------------------------------------------------------
  //PINS
  pinMode(Analog_X_pin, INPUT);
  pinMode(enablePin, OUTPUT);
  //----------------------------------------------------------------------------
  InitialValues(); // averaging the values of the 3 analog pins (values from potmeters)
  //----------------------------------------------------------------------------
  // Stepper parameters
  // setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2000);     //SPEED = Steps / second
  stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
  stepper.setSpeed(1000);
  delay(1000);
}

void loop() {
  ReadAnalog();
  stepper.runSpeed(); // step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadAnalog() {
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    digitalWrite(enablePin, HIGH);  // enable the driver
    stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  } else {
    digitalWrite(enablePin, LOW);   // disable the driver
    stepper.setSpeed(0);
  }
  // Reading the potentiometer in the joystick:
  Analog_X = analogRead(Analog_X_pin);
  // if the value is 25 "value away" from the average (midpoint), we allow the update of the speed
  // This is a sort of a filter for the inaccuracy of the reading
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    stepper.setSpeed(5 * (Analog_X-Analog_X_AVG));
  } else {
    stepper.setSpeed(0);
  }
}

void InitialValues() {
  //Set the values to zero before averaging
  float tempX = 0;
  //----------------------------------------------------------------------------
  // read the analog 50x, then calculate an average.
  // they will be the reference values
  for (int i = 0; i<50; i++) {
    tempX += analogRead(Analog_X_pin);
    delay(10); //allowing a little time between two readings
  }
  //----------------------------------------------------------------------------
  Analog_X_AVG = tempX/50;
  //----------------------------------------------------------------------------
  Serial.print("AVG_X: ");
  Serial.println(Analog_X_AVG);
  Serial.println("Calibration finished");
}


texts: Arduino IDE: sketch window has become unresponsive

texts:
I am very new to all this, but have programmed in other languages using several IDEs. Last night when returning to a coding session, I noticed that the background of the sketch window had gone from white to gray. Then when I tried to continue editing the sketch, I found that I could not make any changes. At all. Clicking anywhere on the screen is futile; the cursor never appears. Text can be highlighted but not copied or pasted. In short, I can’t go on from here at all.
What have I done?


texts: do digital input pins act as a positive or negative

texts: I've gotten contradicting information on the subject.  Some say that digital input pins send out positive voltage, and if it goes to ground (for example) it reads LOW but if the pin is connected to power, it will read HIGH.  On the other hand, some say that the input pin is receiving voltage from either power (+5V) or ground (0V).  which one is it?


texts: Nothing prints in the serial monitor in Arduino - Ide

texts:
Sir, I used Arduino-Uno as programmer and Arduino-Mega 2560 as target and uploaded the below code, I was not able to view the Serial. println lines in the serial monitor, Can you please help. Thanks.

int Led_Builtin = 13 ;

void setup()
{
  Serial.begin(9600);
  pinMode(Led_Builtin,OUTPUT);

}

void loop()
{
  digitalWrite(Led_Builtin,HIGH);
  Serial.println("On");
  delay(300);
  digitalWrite(Led_Builtin,LOW);
  Serial.println("Off");
  delay(100);
  }


texts: Can I place bootloader directly onto Atmega2560 and have USB?

texts:
I am working on a prototype device which I am now on my 2nd board iteration and moving away from it being a shield and wired to an arduino mega2560 board.

I have used the freely available Arduino mega 2560 schematic and incorporated this into my project.

I notice that there are 2 µcontrollers on this schematic, (Atmega2560 & Atmega16U2)

I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

On the searching I have done I'm getting myself terribly confused.
Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)

However, I was intending to flash a boot loader that would make the device appear to a computer (over usb) as a midi controller device.

I am unclear if I can indeed interface a usb port directly to the ATmega2560,  and upload my sketch code AND a midi-over-usb boot loader..
I doubt the advice because the ATmega16U2 (i think) has a built in UART to communicate via usb and that the 2560 does not...

Sorry If this all sounds vague, I'm searched out and confused...

thanks.


texts: Can you power the ESP8266E-12 with any of the 3.3V pins?

texts: If I want to operate the NodeMCU on the 3.3V input with 2.5V to 3.6V; can I use any of the 3.3V pins to do so?


texts:
I'm currently trying to create an Arduino time clock by using the PJRC Time library (http://www.pjrc.com/teensy/td_libs_Time.html). I know that since most of the Arduino boards are running with a 16MHz clock and a single resonator, the time can become "out-of-sync" after a certain period of time.

However, I was wondering if anyone has an idea about the accuracy of the Time library when used on the Arduino DUE with a 84MHz clock. I've been testing it out and so far, the clock has been kept in sync for a few hours. Thanks!


texts:
When I pass an array, and it's len to the constructor of a class. I store the length, and access it later, it's value changes, seemingly at random.

#include "Arduino.h"

#define NUMSENSORS 2
const byte dataPins[] = {A5, A4};

class B {
    public:
        B(byte pin) { _pin = pin; }
        byte getPin() { return _pin; }
    private:
        byte _pin;
};

class A {
    public:
        A(const byte sensorPins[], int len) {
            Serial.print("provided len is: ");
            Serial.println(len);
            _len = len;
            Serial.print("Stored len is: ");
            Serial.println(_len);
            for (int i=0; i<len; i++) { myBarray[i] = new B(sensorPins[i]); }
        }
        B* myBarray[];
        int _len;
        void printLen() {
            Serial.print("Length is: ");
            Serial.println(_len);
        }
};

void setup() {
    Serial.begin(115200);
    A test(dataPins, NUMSENSORS);
    for (uint8_t i=0; i<10; i++) {
        test.printLen();
        delay(100);
    }
}

void loop() {
}

The value of len is fine in the constructor,  but is different when I call it in the function "getLen".

I feel as though it has something to do with pointers. Because if I comment out the for loop in the constructor of A, the value is correct.

Any help would be greatly appreciated, thanks in advance.


texts:
I am using L293d motor driver to drive 2 motors simutaniusly in several direction.

But I am not shure why there is 2 Vcc and 4 GND in this IC.

Can anyone tell explain it?

Thank You...


texts: How do I control 4 LEDs with 2 Digital Outputs?

texts:
In an effort to learn about transistors that seemed easy enough. But I can't get it to work in practice

Can I control 4 LEDs with just 2 digital outputs (High, Low). So I figured I would use the difference between PNP and NPN transistors to create logic gates.

[00,01,10,11]

But I can not seem to get this to work in practice for the life of me.

I read about Charliplexing, but that is n*(n-1), which isn't good enough. I've also read about shift registers, but I'm not sure I fully understand (I'm a noob), and it sounds like you need a minimum of 3 pins. Is what I am trying to do even possible? If not, then why?


texts:
I'm using two tb6600 to control two step motors. It's for letter writing cnc machine.
Moving single axis works fine.
I want to push 2 steppers in the same time along a diagonal.
I tried to calculate ratio x:y, so if x is making more steps than y for 1 y do n x steps. This worked, but machine was shaking no mater how i adjusted delays between step high and low. When i use PWM there is no shaking, but i can't figure out how to make it follow diagonal.
Second try was to use PWM with analogWrite.
if(delayX > delayY){
      analogWrite(stepPinX, 128);
      analogWrite(stepPinY, 128);

      delay(delayY);
      analogWrite(stepPinY, 0);
      delay(delayX - delayY);
      analogWrite(stepPinX, 0);

    }else if(delayX <= delayY){
      analogWrite(stepPinX, 128);
      analogWrite(stepPinY, 128);

      delay(delayX);
      analogWrite(stepPinX, 0);
      delay(delayY - delayX);
      analogWrite(stepPinY, 0);
    }

This doesn't works obviously. It reaches end point, but it doesn't follow diagonal.
If i set duty cycle to 2 or 128 it doesn't matter.
Isn't duty cycle supposed to change speed of stepper motor?
What am i missing here and how can this be done?


texts: Dragino lg01-p problem with serial monitor

texts:
i have a dragino lg01-p lora gateway to which i successfully communivate through lora with an arduino and i can program it through network as expected and seen in its manual with the demo client-server code. However, when i try to open the serial monitor on the side of the dragino, i get this:
Unable to connect: retrying (1)...
Unable to connect: retrying (2)...
Unable to connect: retrying (3)...
Unable to connect: retrying (4)...
Unable to connect: is the sketch using the bridge?
I need to have the serial communication cause i made a little app in C# which gets the data from a COM port. I also tried with Console instead of serial, but still didn't get any results back. This is the code, exactly as is in the examples no the manual
#include <SPI.h>
#include <RH_RF95.h>

// Singleton instance of the radio driver
RH_RF95 rf95;

int led = A2;
float frequency = 868.0;

void setup()
{
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  Serial.println("Start Sketch");
  if (!rf95.init())
    Serial.println("init failed");
  // Setup ISM frequency
  rf95.setFrequency(frequency);
  // Setup Power,dBm
  rf95.setTxPower(13);
  // Defaults BW Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
  Serial.print("Listening on frequency: ");
  Serial.println(frequency);
}

void loop()
{
  if (rf95.available())
  {
    // Should be a message for us now
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len))
    {
      digitalWrite(led, HIGH);
      RH_RF95::printBuffer("request: ", buf, len);
      Serial.print("got request: ");
      Serial.println((char*)buf);
      Serial.print("RSSI: ");
      Serial.println(rf95.lastRssi(), DEC);

      // Send a reply
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
      digitalWrite(led, LOW);
    }
    else
    {
      Serial.println("recv failed");
    }
  }
}


texts: A proper way to get the roll, pitch and yaw values

texts:
TL, DR : What is the method(in terms of sensors and algorithm) to get the roll, pitch angles of an aircraft at any instant.

I am planning to build a hobby aircraft. I am so confused about which kind of sensors should I use and how to use them in order to get the roll, pitch and yaw angles of the aircraft.

I think I also have some problems about understanding the concept. I consider these P, R, Y angles similar to the x,y,z coordinates as if they are able to describe the attitude of a body. If something in the below list contains "nonsense" arguments, please also enlighten me about them.

What I want is to be able to know at any instant:

what is the pitch angle of the aircraft, i.e how much degrees its nose pointing away from the horizontal plane of the earth.
what is the yaw angle, i.e to what direction(north, east etc) is the aircraft pointing through.
what is the roll angle, i.e what is the angle between aircrafts body surface ( wing to wing x tail to head surface ) and the horizontal plane of the earth/sky.

In some sources there is something going on as the importance of order of the application of roll,pitch and yaw. But I cannot understand why this is related.

I have used accelerometer values by inputting them into some formulas on the internet(those arctangent formulas, which everybody uses but nobody explains well) to get the roll and pitch values. However could not understand how to manipulate them in order to meet my requirements(different axis orientations of the sensor).

I also have basic understanding about what a gyroscope is.

I have an MPU6050(Accelerometer+Gyroscope).

Thanks in advance.

P.s : my goal is to build a quadcopter but I guess in order to understand these concepts a fixed wing standard plane model.


texts:
I'm using the Arduino framework on an ESP32 based board. The board has an SD card slot, but I'm not going to use it.
Anyway, I need to store somewhere the certificates. To the the firmware I've just hardcoded them into the code:
const char *rootCABuff = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB\n" \
...
"hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq\n" \
"-----END CERTIFICATE-----\n";

const char certificateBuff[] = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDWTCCAkGgAwIBAgIUZXjPNnJFXMntXOki9BT+QmDFciUwDQYJKoZIhvcNAQEL\n" \
...
"gGXtqlgPnenkZPTaBr9c8o+WjgQXFLM+Jwnw3/53dUI9zBcybTaptI63o3Ct\n" \
"-----END CERTIFICATE-----\n";

const char privateKeyBuff[] = \
"-----BEGIN RSA PRIVATE KEY-----\n" \
"MIIEpAIBAAKCAQEAuuKsFy98/xsJclnWo0d+qm8KImLEILB64BbH7WaYi3NnznLg\n" \
...
"uHfBLQQDrA0HDRvYpAUNw/b2H4dpUK/nGM4FFVMP7V8RM2t2923nhQ==\n" \
"-----END RSA PRIVATE KEY-----\n";

Of course this is not suitable for production where each unit will have a different set of certificates.
So wonder what is the best way to store them.
The obviously idea is into flash. So I tried to enhance my settings class, based upon the Preferences library. In the official documentation I read:

String values are currently limited to 4000 bytes. This includes the null terminator. Blob values are limited to 508000 bytes or 97.6% of the partition size - 4000 bytes, whichever is lower.

But if I do something like this:
Preferences prefs;
prefs.begin("settings", false);
Serial.println(prefs.freeEntries());

it return 460, even if I still have plenty of flash:
Flash: [=======   ]  73.8% (used 967234 bytes from 1310720 bytes)

Is there another library more suitable to store such a data that can be used with Preferences?


texts:
I'm looking to create a USB device that would  be basically a HID keyboard. I am able to do that with Uno. I flash new firmware with a HID keyboard descriptor and on the arduino side I loop and check for button presses. Based on butotn presses I send the report.

What I would like to add to this is option to send some data from a PC and based on that data do something (like turn an LED on.)

Here is an example:

loop() {
  check_and_send_buttons();
  uint8_t inputByte = get_input(); //new
  handle_input(inputByte); //new
}

I'm on Linux and I tried sending some data via hidrawX but that did not work out.
Any ideas?

I'm willing to also write new device driver for Linux if needed.


texts:
Looking for a great way to detect when someone touches thread, or if 4 people touch thread etc.

I'm not looking for a hand count, but I'm going to try to translate it into MIDI for use in a project.

Am I looking for a form of capacitive sensor?


texts:
I'm making an arduino program for a buzzer that you can record notes and song for and then play them back. I have 2 arrays that hold both pitch and if a note is being played. I continue to get errors that say expected unqualified-id before 'public'.

Does anybody know how to fix this?

void setup()
{
 Serial.begin(9600);
 pinMode(5, INPUT_PULLUP);
 pinMode(14, INPUT_PULLUP);
 pinMode(12, INPUT_PULLUP);
}

void freePlayMode()
{
    int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }
}

void recordMode()
{
 int readS2 = digitalRead(12);
 if (readS2 == LOW)
 {
  rec();
 }
 else
 {
  if (readS2 == HIGH)
  {
    playBack();
  }
 }
}

void rec()
{

static public int recordings[99999999] = {NULL};
static public int notes[99999999] = {NULL};
int state;
static unsigned long i = 0;
int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }

  if (i < 99999999)
 {
  if (readB == HIGH)
  {
    state == 0;
  }
  else
  {
    state == 1;
  }
  recordings[i] = state;
  notes[i] = readP;
  i++;

 }
}

void playBack()
{

}

void loop()
{
int readS1 = digitalRead(14);
if (readS1 == LOW)
{
  freePlayMode();
}
else
{
  if (readS1 == HIGH)
  {
    recordMode();
  }
}

}


texts: What are the problems with using an Arduino in a production environment?

texts:
I am thinking about making a real project using arduino to earn money.

What could be the objective reasons (from both a technical and a business perspective) to not use an Arduino in a real profitable project?


texts: Understanding how methods and pointers inside a function work

texts:
After this question i starteted going deep with the theory, and started studyng step-by-step with the "Beginning C, for Arduino "
Jack Purdum.

I finished to study the functions chapter, but i still have some doubts on the code, i hope this will be not a dumb question.

Why there is a Method "Print" not a Data Type inside the Function Argument List?

static void printImuData(Print &printer, int16_t Time0,
        int16_t AcX, int16_t AcY, int16_t AcZ,
        int16_t GyX, int16_t GyY, int16_t GyZ)
{
    printer.print(Time0); printer.print(",");
    printer.print(AcX);   printer.print(",");
    [...]
}

[...]

printImuData(dataFile, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);
if (Serial_plus_SD)
    printImuData(Serial, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);

I though the answer was "because you can pass data to a function by-value or by-reference" in fact the first input in the argument list is the left value (memory address) of a Method, but i am very confused.

Function arguments are used to pass data to the function that it may need to perform its task.

I tried to answer to the following questions to understand the code.

1. What task does this function perform?

The function will print some data on a Serial Monitor or SD Card

2. What data do i need to send to the function?

I need to send one Method through the left value of a pointer and 7 intergers.
I can't understand why a method.

3. What data do I get back from it?

Nothing because is a void, it will perform some task inside the function (print inside the object thas is pointed?) but nothing will return to the caller.

In the book  basic example is a function that returns the value 0 or 1 if is a Leap Year.

The function argument is an int and returns an int.

void loop()
{
    if (Serial.available() > 0) {
        int bufferCount;
        int year;
        char myData[MAXCHARS + 1]; // Save room for null
        bufferCount = ReadLine(myData);
        year = atoi(myData); // Convert to int
        Serial.print("Year: ");
        Serial.print(year);
        Serial.print(" is ");
        if (IsLeapYear(year) == 0) {
            Serial.print("not ");
        }
        Serial.println("a leap year");
}
}
/*****
Purpose: Determine if a given year is a leap year
Parameters:
int yr The year to test
Return value:
int 1 if the year is a leap year, 0 otherwise
*****/
    int IsLeapYear(int yr)
    {
    if (yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0) {
        return 1; // It is a leap year
    } else {
        return 0; // not a leap year
    }
}
/*****
Purpose: Read data from serial port until a newline character is read ('\n')
Parameters:
char str[] character array that will be treated as a null-terminated string
Return value:
int the number of characters read for the string
CAUTION: This method will sit here forever if no input is read from the serial port
and no newline character is entered.
****/
int ReadLine(char str[])
    {
        char c;
        int index = 0;
        while (true) {
        if (Serial.available() > 0) {
        index = Serial.readBytesUntil('\n', str, MAXCHARS);
        str[index] = '\0'; // null termination character
        break;
        }
    }
    return index;
}

Like in my the last question, I have a civil engineer background and i am a self-taught, so is my first time with coding :)

Thank you for your patience.


texts:
I plan on purchasing a Nano clone, an Ethernet shield (ENC28J60), an LCD and a DHT22 humidity + temperature sensor. This will be used in a wine cellar to monitor relative humidity and temperature.

The DHT sensor, LCD and Nano all operate on 5V logic. The Ethernet shield does not operate at 5V, but rather at 3.3V.

Does the Nano have a way to connect the two, will they work anyway (probably not), or should I use a CD4050 that is recommended on adafruit?

Any guidance is appreciated; I'm still amazed in what $10 in parts can do.

Also, in regards to the DHT22 sensor, what do I need in terms of a resistor? I've seen some people say you absolutely need a 4.7K resistor on the data pin for "pull up", and  others who say it's unnecessary. Can someone give a definite answer, either way?

Edit, wrong link on my nano clone.


texts:
I am trying to run a stepper motor using an Arduino stepper motor shield like the Adafruit V1 motor shield. In my code I am just trying to get the motor to rotate forwards and backwards. When I first try uploading and running the code I can get a forward and reverse rotation, but then the motor begins jittering inconsistently. I have tried changing my wiring setup but generally get the same results. Here is the data sheet for the motor I am using. I have the board it connected to a 12v battery. I also got the same problem when trying to drive the motor using just an H-drive chip. I have included my code below as well as a picture of my wiring. Here is a video of the jitter.
#include <AFMotor.h>
AF_Stepper motor(200, 1);
void setup() {
Serial.begin(9600);           // set up Serial library at 9600 bps
Serial.println("Stepper test!");

motor.setSpeed(120);  // 10 rpm

motor.step(100, FORWARD, SINGLE);
motor.release();
delay(1000);
}

void loop() {
motor.step(200, FORWARD, DOUBLE);

delay(1000);
motor.step(200, BACKWARD, DOUBLE);
delay(1000);
}


texts: Playing WAV file from Arduino Uno using Ethernet R3 Shield

texts:
I'm trying to start a project where I have a 6 sec recording (wav file: 8 bit, 8 or 16 kHz, mono) on a micro-SD card and want to play it through my Arduino Uno on an 8 Ohm, 0.1 W speaker. I've looked at many different forums and threads for how to do this. One that continually comes up is this link, but this is for the Due and I can't figure out how to adapt for the Uno.

The important bit is I am using an Ethernet R3 shield which has a built in micro-SD card reader. Much of the code and tutorials I found use the TMRpcm library, setting the speaker pin to 9, the SDChipSelectPin to 4, with various wire connection geometries depending on which tutorial you read. I really need help trying to figure out how the wiring is supposed to go. I, honestly, do not understand what's going on and am hoping someone will take the time and can explain this pretty pedagogically. Currently, no matter what I try, I just hear high-pitched static or fast periodic noises.


texts:
Based on this approach I wanted to implement a function for formatted printing data to the serial monitor. I tried the code below:

int PIN = 12;

void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  sprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

void setup() {
  Serial.begin(9600);
  Serial.println("serial monitor has been set up");
  char buf0[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf0, "pin %i configured to output", PIN);
  Serial.println(buf0);
  _printf("pin %i configured to output", PIN);
  char buf1[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf1, "pin %i configured to output", PIN);
  Serial.println(buf1);
  _printf("pin %i configured to output", PIN);
  pinMode(PIN, OUTPUT);
  char buf2[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf2, "pin %i configured to output", PIN);
  Serial.println(buf2);
  _printf("pin %i configured to output", PIN);
  char buf3[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf3, "pin %i configured to output", PIN);
  Serial.println(buf3);
  _printf("pin %i configured to output", PIN);
}

void loop() { }

But it gives me some weird output:

serial monitor has been set up
pin 12 configured to output
pin 2263 configured to output
pin 12 configured to output
pin 2234 configured to output
pin 12 configured to output
pin 2205 configured to output
pin 12 configured to output
pin 2176 configured to output

What do 2263 and 2269 mean? Why does it happen only inside the function? What is my mistake and how can I fix it?


texts: Ultrasonic Sensor and Motor Driver Shield

texts: im new to arduino and am making an arduino car. the motor driver shield covers the ports (am connecting an ultrasonic sensor) and i know that we can connect it to the 'holes' on the motor driver shield (l293d) but i do not have a solder or header pins. there's a str t lockdown and i cannot get any of those (deliveries have been put on hold). can i make a makeshift arrangement? (refer img): it is a little loose, is there any fix using jumper wires or any other arrangement? please let me know! *can i connect the ultrasonic sensor to the arduino instead alongside the motor driver shield?


texts: usb host shield + wireless mouse (Read 5 times)

texts:
hello guys i have a problem ,
i have a usb host shield v2.0 from circuits @home  attached to an arduino mega and to a usb wireless reciever mouse ,
this is the serial monitor  output :
x=0 dy=3
dx=0 dy=-1
dx=0 dy=-1
dx=0 dy=-1
dx=0 dy=-1
dx=0 dy=-1
dx=0 dy=1
dx=0 dy=-2
dx=0 dy=-2
dx=0 dy=2
dx=0 dy=9
dx=0 dy=6
dx=0 dy=-1
dx=0 dy=2
dx=0 dy=-1
dx=0 dy=-1
dx=1 dy=0
dx=2 dy=0
dx=1 dy=0
dx=2 dy=0

and this is the code from the library usbhidbootmouse :
#include <hidboot.h>
#include <usbhub.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

class MouseRptParser : public MouseReportParser
{
protected:
    void OnMouseMove    (MOUSEINFO *mi);
    void OnLeftButtonUp (MOUSEINFO *mi);
    void OnLeftButtonDown   (MOUSEINFO *mi);
    void OnRightButtonUp    (MOUSEINFO *mi);
    void OnRightButtonDown  (MOUSEINFO *mi);
    void OnMiddleButtonUp   (MOUSEINFO *mi);
    void OnMiddleButtonDown (MOUSEINFO *mi);
};
void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{
    Serial.print("dx=");
    Serial.print(mi->dX, DEC);
    Serial.print(" dy=");
    Serial.println(mi->dY, DEC);
};
void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi)
{
    Serial.println("L Butt Up");
};
void MouseRptParser::OnLeftButtonDown   (MOUSEINFO *mi)
{
    Serial.println("L Butt Dn");
};
void MouseRptParser::OnRightButtonUp    (MOUSEINFO *mi)
{
    Serial.println("R Butt Up");
};
void MouseRptParser::OnRightButtonDown  (MOUSEINFO *mi)
{
    Serial.println("R Butt Dn");
};
void MouseRptParser::OnMiddleButtonUp   (MOUSEINFO *mi)
{
    Serial.println("M Butt Up");
};
void MouseRptParser::OnMiddleButtonDown (MOUSEINFO *mi)
{
    Serial.println("M Butt Dn");
};

USB     Usb;
USBHub     Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser                               Prs;

void setup()
{
    Serial.begin( 115200 );
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    Serial.println("Start");

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

    delay( 200 );

    HidMouse.SetReportParser(0, &Prs);
}

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

i wanna know the dx is equal to 1 when i press the left button on mouse and is equal to 2 when i press the right button on mouse and the dy is responsible for the x and y coordinates from - to + ? how a single value is responsible for x and y both ?


texts:
I'm currently attempting to take readings from 10 thermocouples using an Arduino Mega. I've been using MAX31850 1Wire Thermocouple Modules (with the Adafruit breakout) to perform the readings, but their response time has been very slow (~500ms each). I'm not sure if most of this latency is coming from the IC, or from the communications protocol, or perhaps even the DallasTemperature library.

For my application, I need to be able to read all 10 thermocouples in at most 250 ms (and faster would be better) and so I can afford up to 25ms per thermocouple. I would also like to be measuring with a precision of about 1-2 F.

I assume I will probably have to use a different amplifier, and I've seen recommendations online of using an external ADC to achieve higher speeds, which I would be happy to do, but I don't understand why that would make a substantial difference on speed since the onboard ADC can already sample at about 1/10 ms.

I would greatly appreciate any recommendations on how to achieve these speeds.


texts: How to connect new OV7670 FIFO to Arduino?

texts:
I bought a new OV7670 FIFO camera to connect to my Arduino UNO a few days ago.

The picture of the cam board:

I found this forum, it is nice try but it looks chaotic and confusing with about 50 pages, where you can't find where the questions and where the answers are.

I also found this library which is for non-FIFO board and could not apply to my project. I also read the OV7670_FIFO and OV7670 and AL422 datasheets and I read I2C protocol and basics; and there are many success story on the internet but there is no schematic on them.

The problem is, I can't find any simple example for FIFO with schematic to start with. I don't know if this camera is so new or it is so hard to understand, this problem getting so serious that somebody wrote a book named "Beginning Arduino ov7670 Camera Development" about it, but I think it is a matter of an Arduino to FIFO cam schematic and example code. I ask if there is a such schematic and code for it on the web or how can I connect them?


texts: Why is my radio circuit working with other arduinos but not the Pro Minis?

texts:
I have some Arduino Pro Minis. I have both the 3.3V/8MHz and 5V/16MHz versions. I'm trying to get them to work with the nRF24L01 RF modules.

I've lightly modified some example code from the RF24 library, and gotten it working with an Arduino Micro and Nano. Basically, I just send an increasing integer from one to the other, and the receiving one displays on an LCD the latest number it received, which lets me know if a transmitter is working.

So that all works. Now I'm trying to use a Pro Mini (tried both 3.3V and 5V versions) to transmit instead of the Nano I was using before. The regulator is a 3.3V LDO. The battery is supplying that LDO and the RAW pin of the Pro Mini with ~8.5V, which should be good. Measuring the voltage out of the LDO gives 3.3V.

I looked at the pinout of the Pro Mini, and I believe I've hooked up the module to the correct MOSI/MISO/SCK pins, as well as pins 7 and 8 for the module's CE and CSN pins.

Buuut... it's not working. Nothing is appearing on the LCD. I know the nRF and its header thing work fine, because I can pop the exact one into the circuit with the Nano that works.

Even more strangely, I'm pretty sure the Pro Minis are getting programmed successfully. I can upload the Blink example to them, and that works. I'm using an Adafruit FTDI friend to upload, and that appears to be working (compiles, uploads, etc without error).

Here's the code I'm using for the transmitter, it's pretty simple. Does anyone have any suggestions? Thanks in advance. Let me know if there's anything I forgot to include.

edit: It won't let me include more than two links because of my low rep, so I can't include images of my ciruit/wiring. But I'll manually write it out here:

The numbering here is with respect to the pins in the nRF link above.

nRF module pin           Arduino Pro Mini Pin
1 (GND)           GND rail (not on Arduino)
2 (VCC)           3.3V rail (from external regulator)
3 (CE)           Digital pin 7
4 (CSN)           Digital pin 8
5 (SCK)           Digital pin 13
6 (MOSI)           Digital pin 11
7 (MISO)           Digital pin 12
8 (IRQ)           Not connected to anything


texts:
What is an "Arduino core"?

Are there many different "Arduino cores"? such as a core that applies to LCD
displays, another core that applies to servos, etc.?


texts: Can I detect with software when a PIR sensor is physically connected to Arduino?

texts:
I'm creating a circuit using an Arduino Nano + ESP8266 to allow LED remote (via mobile app) activation and configuration (RGB colour, timeout, etc.). The circuit also has an optional PIR sensor to switch on the LED when someone enters the room.

I'd like the circuit to behave differently when the PIR is physically connected to the Arduino (i.e. to light the LED in a different colour) but I have no idea of how detect if the sensor is physically connected to the circuit.

I tried reading the value of the Arduino PIN but (obviously) the signal is LOW whether nothing is detected by the PIR or is not physically connected.

I have two different PIR detectors that I can use for the project:

Arduino Compatible PIR Motion Detector (Description)
DFRobot PIR Detector (Description, Schematic)

Thank you for your time. If there is missing information in my question, please tell me and I will add it.


texts: Storage usage of methods compared to copied code

texts:
When you have really small snippets of code that are repeated several times in your micro controller program, is it better to write a method? I mean better in terms of performance and storage usage. I know that when programming for PC, code repetition is a big no go, but what about micro controllers?

In the following example (Arduino Nano with Adafruit 2,8" cap touch display) the snippet should look if the back button is pressed in several screens. I checked in the Arduino IDE how much storage each version takes:

Version 1, 15114 Bytes for complete program:

void battScreen(TS_Point p){
  // some other code
  // ....
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void alarmScreen(TS_Point p){
  // some other code
  //...
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void pumpScreen(TS_Point p){
  // some other code
  // ...
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

Version 2, 15234 Bytes for complete program:

void checkBack(TS_Point p){
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void battScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

void alarmScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

void pumpScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

As you can see, version 2 with the extra method takes 120 Bytes more storage. Is there a rule of thumb when it makes sense to create a new method instead of copying code?


texts: Breadboard-to-Arduino wiring with flat flex cable assemblies?

texts:
I want to wire Arduino Due connectors to a breadboard 8-at-a-time, so they're easier to remove and more reliable.

I tried these Flat Flex Cable Assemblies (FFC assemblies) terminated with "solder lugs" from Digi-Key, but the pins are just a little too short to penetrate the Arduino connectors well.  Similarly they barely reach into to the breadboard contacts, so they tend to fall out.  Anyone find a workable product for this?

This solution is good but requires a lot of manual soldering.  Looking for prepackaged.


texts:
I connected my gps module (NEO-6M) with esp32doit-devkit-v1 board. The module provided data but many data are missing.

My pin configuration:

GPS ------- ESP32
VCC ------- 3v3
GND ------- GND
TX -------- RX2 (pin 16)
RX -------- TX2 (pin 17)

Baud Rate: 9600

My code:

#include <Arduino.h>
#include <TinyGPS++.h>

#define TXD2 17
#define RXD2 16

TinyGPSPlus gps;

void setup()
{
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  Serial.println("Started......");
}

void loop()
{
  while (Serial2.available())
  {
    Serial.write(Serial2.read());
    // gps.encode(Serial2.read());
    // if (gps.location.isValid())
    // {
    //   Serial.print("Latitude= ");
    //   Serial.print(gps.location.lat(), 6);
    //   Serial.print(" Longitude= ");
    //   Serial.println(gps.location.lng(), 6);
    // }
  }
}

OUTPUT


texts:
My need is to connect an Arduino board (any board that has around 3 UARTs support) to a host PC via USB and expose the 3 UART connections as 3 USB devices (say /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyUSB2) in the host PC. From my search, I found Arduino Mega 2560 supports upto 3 UARTs. My question is can we expose these UARTs into individual USB ports to the host system?

Thanks,
Alexander


texts: Using Arduino's hardware serial to control SIM900

texts:
I have a SIM900 board which has a serial interface. I'm trying to control it using Arduino Uno. I've tried using SoftwareSerial on pins 10 (RX) and 11 (TX) to talk to my board. It works OK with different baud rates (SIM900 has auto-bauding). I'm connecting pin 10 directly to my board, but pin 11 is connected through a voltage divider in order to lower voltage from 5 V to 2.8 V (SIM900 uses 2.8 V CMOS logic levels).

But now I want to use Arduino's hardware UART to talk to SIM900. I'm using pins 0 and 1 with similar design as above (also using voltage divider). I just can't get it to work. No matter what I do I can't see any communication. I've tried different baud rates, but it just doesn't work. Here is my code:

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

  delay(10000);
  Serial.write("AT\r");
  delay(1000);
  if (Serial.available())
  {
    digitalWrite(13, HIGH);
  }
}

void loop()
{
}

So I should see a LED light up but nothing happens (SIM900 responds with "\r\nOK\r\n" to "AT\r"). What am I doing wrong?


texts: Shift between the carrier frequency of the signal transmitted with arduino and my garage door RC (433 mhz)

texts:
I have this 433 mhz transmitter and receiver for arduino.

I want to replay my garage door remote control with this transmitter so I reversed the RC (remote control) signal with RTL-SDR/sdrsharp and audacity.
It is not working.

Why is there a shift between the carrier frequency of the signal transmitted with arduino (RH_ASK library) and my garage door RC ?
How can I change this ?


texts: send command to Slave and receive response over I2c

texts:
so I have an Arduino mega as the master and an attiny84 as the slave
the master can send a command S to the slave and the slave should respond with TRUE so here is my code:
master:
bool GetOnline(){
      Serial.println("Sending Status Command ");

      if(Address != NULL){
        String res;
        Wire.beginTransmission(Address);
        Wire.write('S');
        Wire.endTransmission();
        Wire.requestFrom(Address, 4);
        while (Wire.available())
        {
          char inChr = Wire.read();
          res += inChr;
        }

        Serial.print("Device responce: ");
        Serial.println(res);
        if(res == "TRUE"){
          return true;
        } else {
          return false;
        }
      }
    }

Slave:
void normalReceive(uint8_t howMany) {
  while(Wire.available())//if wire is avaliable
  {
    char command=Wire.read();//state read the recived command from master, high or low
    MySerial.print("recived: "); MySerial.println(command);
    switch(command){
      case 'A': digitalWrite(LEDReboot,LOW);
       break;
      case 'B': digitalWrite(LEDReboot,HIGH);
       break;
      case 'S': Wire.write("TRUE");
       break;
      case 'R': resetFunc();
       break;
      default: MySerial.print("recived: "); MySerial.println(command);
       break;
    }
  }
}

void normalRequest() {
  MySerial.println("Request SN");
  Wire.write(sn);
  }

now the issue is when I request from the slave it returns the SN rather than the expected TRUE
I am very new to I2C so any help is appreciated.


texts:
Im trying to make an arduino project which uses IR remote control and does certain thing.
My doubt is the weather the hex codes of some remotes be similar
and if they are how to tell arduino to only take inputs from my IR remote so there is no interference from any other IR remote based applications like tv.
Or should i make a custom IR remote and define some custom hex codes and then there will be no interference ?
Or is there any other work around open to suggestions here.


texts: I can not upload hex files outside of the Arduino IDE to my Pro Micro

texts:
I have a strange problem. I am trying to upload a .hex file to my lovely Arduino Pro Micro, but am unable to do so. If I use the Arduino IDE, it goes through perfectly fine and uploads the sketch. However, if I try to use avrdude from the terminal I get:

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

My commandline is:

avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -t

and the full output is:

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
    Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: leave prog mode
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: exit bootloader

Thank you for any help, it is greatly appreciated.

--Dominic


texts:
In my recent project, I want to set my time according to the requirement. And somehow I'm able to manage that. But when I'm decreasing my time value then one weird problem happens. When decreasing my time value, when I reach ZERO (0) and when I again decrease value then it shows the maximum range of that data type even if I put the condition for stop value at ZERO(0).

My code is below:

const int kPinSw1 = 2;
const int kPinSw2 = 3;

int plusBtnIncState = 0;
int lastPlusBtnIncState = 0;

int minusBtnDecState = 0;
int lastMinusBtnDecState = 0;

unsigned long currentMillis;
unsigned long previousMillis;
unsigned long interval = 0UL;

void setup() {
  Serial.begin(9600);
  pinMode(kPinSw1, INPUT_PULLUP);
  pinMode(kPinSw2, INPUT_PULLUP);
}

void loop() {
  //---------------INC_TIMER---------------//
  plusBtnIncState = digitalRead(kPinSw1);
  if(plusBtnIncState != lastPlusBtnIncState) {
    if(plusBtnIncState == HIGH) {
      interval = interval + 1000;
    }
    delay(50);
  }
  lastPlusBtnIncState = plusBtnIncState;

  //---------------DEC_TIMER---------------//
  minusBtnDecState = digitalRead(kPinSw2);
  if(minusBtnDecState != lastMinusBtnDecState) {
    if(minusBtnDecState == HIGH) {
      interval = interval - 1000;
      if(interval <= 0) {
        interval = 0;
      }
    }
    delay(50);
  }
  lastMinusBtnDecState = minusBtnDecState;

  //---------------------------------------//
  Serial.print("Int:");
  Serial.print(interval);
  Serial.print("\n");
}

And output:

Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296

As you can see in output when I reach ZERO and then again decrease the value then the value is like 4294966296 instead of ZERO. I put the logic for that if we reached ZERO or less ZERO then it must stay at ZERO. I don't understand why this happens. Please suggest me something.


texts: Arduino NANO (CH340) error while flashing bootloader

texts:
Ok. So I'm close to tearing me hair out on this one.

I have a batch of cheap Arduino Nano clones, that just straight up won't work. (I HAVE gotten one of them to work, but I suspect that was by pure coincidence)

Anyway, I feel like I've tried everything to make them work.
I am consistently getting

  Device signature = 0xffffff

errors from avrdude, which I believe is a hardware problem. Up til now I have tried:

Installed CH340 drivers, no difference
Tried to burn bootloader using Uno as an ISP (with 10uF cap between reset and ground!)
Tried the "(Old Bootloader)" option in the IDE

All I have left is to desolder the entire board and troubleshoot each single component, but... no, I want to keep my sanity intact, thaaank you!

Any ideas on how I should move forward here?


texts: Arduino crashing during serial print for no obvious reason

texts:
I've written some Arduino Code which kept crashing and i couldn't find out why. Then i reduced the code as much as i could in order to see the problem.
The reduced code currently doesn't do anything extraordinary except printing some strings over the serial line.

This is the reduced code:

void setup()
{
  Serial.begin(9600);
  Serial.print("Begin\r\n");
  send_wifi_beacon();
}
void loop()
{
  delay(1000);
}
void send_wifi_beacon()
{
  send_wlan_chip_command("AT+CIFSR");
  Serial.print("notreached"); // this part is never reached
  send_data_over_network(); // can't remove this line otherwise the crash won't happen which is weird since this is never called
}
void read_response_from_serial()
{
  delay(2000);
  Serial.print("==-1\r\n"); // crashes here
}
void send_wlan_chip_command(char* command)
{
  Serial.print("Sending command to wifi module: ");
  Serial.print(command);
  read_response_from_serial();
  Serial.print("Command response: ");
}
// this function is never called, since the crash happens before the call, but it can't be removed otherwise the crash won't happen
// also it can't  be altered then, the crash also will not happen.
void send_data_over_network()
{
  char number[3] = "12";
  //char number[3] = "";
  char length_of_payload[20] = "0123456789012345678"; // 20 digits if assuming 64 bit integer is the maximum this code will ever run on
//  char length_of_payload[20] = "";
  char *command;

  command = malloc(26);
  command = "AT+CIPSSEND";
  strcat(command, number);
  strcat(command, ",");
  strcat(command, length_of_payload);
  send_wlan_chip_command(command);
  free(command);
}

This is the according output:

  Begin Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin

Which means that the arduino keeps crashing and resetting. This goes on forever.

The weird thing is, if I change the following two lines to: (in the"send_data_over_network" function as in example above)

char number[3] = "1"; // changed from => char number[3] = "";
char length_of_payload[20] = "123"; // changed from => char length_of_payload[20] = "0123456789012345678";

The output now changes to :

I call this behaviour weird since it shouldn't have any influence on the result because this function(send_data_over_network) is never called in the crash example from before.

Troubleshooting options i already tried:

Reinstalling Arduino IDE , i tried with mutliple versions 1.8 , 1.6, 1.4. 1.0
Different Arduino Boards (Arduino Uno and Arduino Mega)
Different Laptops (since i thought maybe it's related to power issues of my laptop)

Maybe it's something obvious and i just can't see it, but i already spent +16h debugging, so help would be really appreciated.


texts: Sending MPU6050 data over serial to Java/C# Program

texts:
I am using a MPU6050 Accelerometer/Gyro breakout (GY-521) to retrieve data and send it to a java program. I have tried several ways, but I couldn't find a way to send the float values calculated from the Arduino over Serial. Could you please let me know a good way of serial communication with Arduino and a Java Program? Thanks in advance.

UPDATE:

Thank you for your comments and replies. What I have tried is the I2Cdev library code. I could work with it without any issue. Code is in this link. I also could run the processing code to get a visual output. But the problem I have i that I'm not able to send the accelerometer and gyro data to a Java/C# program and process it from there. I tried sending an array of FIFO bytes from the Arduino and convert it from the C# code and processing code, but it didn't give me correct results. Now what i did was, just to send a string of values and receive it from the C# program. But I don't know whether it's good method. I would be glad if you could help me in this. Thanks again.

Arduino

#ifdef OUTPUT_TEAPOT
        // display quaternion values in InvenSense Teapot demo format:
        teapotPacket[2] = fifoBuffer[0];
        teapotPacket[3] = fifoBuffer[1];
        teapotPacket[4] = fifoBuffer[4];
        teapotPacket[5] = fifoBuffer[5];
        teapotPacket[6] = fifoBuffer[8];
        teapotPacket[7] = fifoBuffer[9];
        teapotPacket[8] = fifoBuffer[12];
        teapotPacket[9] = fifoBuffer[13];
        Serial.write(teapotPacket, 14); //Serial.write(buf, len)
        teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
    #endif

    #ifdef OUTPUT_ACCEL_STR_RAW
        mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

        String accelGyroRaw = "STX,";
        accelGyroRaw += ax;
        accelGyroRaw += ',';
        accelGyroRaw += ay;
        accelGyroRaw += ',';
        accelGyroRaw += az;
        accelGyroRaw += ',';
        accelGyroRaw += gx;
        accelGyroRaw += ',';
        accelGyroRaw += gy;
        accelGyroRaw += ',';
        accelGyroRaw += gz;
        accelGyroRaw += ',';
        accelGyroRaw += "ETX";

        Serial.println(accelGyroRaw);

    #endif

C# Code

class Program
{
    static SerialPort port = new SerialPort("COM7", 115200);
    //static int serialCount = 0;
    //static int aligned = 0;
    //static char[] teapotPacket = new char[14];
    //static float[] q = new float[4];

    static void Main(string[] args)
    {

        Console.WriteLine("****** Serial Console Read ********");
        port.Open();
        port.DataReceived += port_DataReceived;

        Console.Read();
    }

    static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        string s = port.ReadLine();
        string[] accelGyroVals = s.Split(',');
        string[] accl = new string[3];
        string[] gyro = new string[3];

        if (accelGyroVals[0] == "STX" && accelGyroVals[accelGyroVals.Length - 1] == "ETX\r")
        {
            accl[0] = accelGyroVals[1];
            accl[1] = accelGyroVals[2];
            accl[2] = accelGyroVals[3];

            gyro[0] = accelGyroVals[4];
            gyro[1] = accelGyroVals[5];
            gyro[2] = accelGyroVals[6];

            Console.WriteLine("a : " + accl[0] + " , " + accl[1] + " , " + accl[2] + "\t g : " + gyro[0] + " , " + gyro[1] + " , " + gyro[2]);
        }

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        if (port.IsOpen)
        {
            port.Close();
        }
    }
}

Sorry for this for lengthy code and if my question is unclear. It's my first time to work with an IMU. Thank you.


texts:
I buy ESP8266MOD chip and flashed with FW: MicroPython v1.11.

Now I have problem connect  to my home network via DHCP (like other device in home).

Below is code which I send to ESP8266 via ESPlorer:
Send:import esp
Send:esp.osdebug(0)
Send:import network
Send:sta_if = network.WLAN(network.STA_IF)
Send:ap = network.WLAN(network.AP_IF)
Send:ap.active(False)
Send:sta_if.active(False)
    Response from ESP: state: 5 -> 0 (0)
    Response from ESP: rm 0
    Response from ESP: pm close 7
    Response from ESP: del if0
    Response from ESP: usl
    Response from ESP: mode : null
    Response from ESP: fpm open,type:2 0

Send:sta_if.active(True)
    Response from ESP: fpm close 3
    Response from ESP: mode : sta(2c:f4:32:14:72:fd)
    Response from ESP: #5 ets_task(4020f4d8, 28, 3fff9468, 10)
    Response from ESP: add if0

Send:sta_if.connect("SSID", "PASS")
    Response from ESP: scandone
    Response from ESP: state: 0 -> 2 (b0)
    Response from ESP: state: 2 -> 3 (0)
    Response from ESP: state: 3 -> 5 (10)
    Response from ESP: add 0
    Response from ESP: aid 6
    Response from ESP: cnt
    **Response from ESP: connected with SSID, channel 7**
    **Response from ESP: dhcp client start...**
    **Response from ESP: pm open,type:2 0**

Send:sta_if.isconnected()
    Response from ESP: False

** after few minutes ***
    Response from ESP: bcn_timout,ap_probe_send_start
    Response from ESP: ap_probe_send over, rest wifi status to disassoc
    Response from ESP: state: 5 -> 0 (1)
    Response from ESP: rm 0
    Response from ESP: pm close 7
    Response from ESP: scandone
    Response from ESP: state: 0 -> 2 (b0)
    Response from ESP: state: 2 -> 3 (0)
    Response from ESP: state: 3 -> 5 (10)
    Response from ESP: add 0
    Response from ESP: aid 6
    Response from ESP: cnt

    Response from ESP: connected with SSID, channel 7
    Response from ESP: dhcp client start...
    Response from ESP: pm open,type:2 0

It's like that DHCP doesn't return IP.
If I config ESP with static IP then connect in few seconds after send a command.

How to debug why DHCP can't get IP on ESP?

I tested with:
 - 3 routers
 - with different SSID, password and channels

Thanks.

(other device connect on the same network with no problem)


texts:
I plan on making an Arduino project for reminding a parent to take a child from a car. In order to power the project I though on using a solar panel. Since I can't rely on having solar power all the time I'll need to use rechargeable batteries and charge them with the solar panel.

The problem is that from reading about the subject it is clear that it can be dangerous as far as battery go up in flame in some cases, especially due to high heat.

My car can get into very high temperature when parked outside so this scenario is very likely to happen.

Can someone please direct me to reading materials about using solar power in a very safe way?


texts: Multiple 3-wire SPI sensor interfacing with Arduino

texts:
I want to connect 4 MAX6675 thermocouple to Arduino.
MAX 6675 description.

It comes with its own Arduino library. library link.

I tested the example code for one sensor and it works perfectly. Now I want to connect all the four sensors to Arduino using minimum GPIO pins possible.

I connected - (for 2 sensors only for initial testing):

D7 -> clk (slave 1) ->clk (slave 2)
D3 -> so (slave 1) ->so (slave 2)
D4 -> cs (slave 1)
D5 -> cs (slave 2)

My code (I modified the original example code a bit):

// this example is public domain. enjoy!
// www.ladyada.net/learn/sensors/thermocouple

#include "max6675.h"

int thermoCLK = 7;
int thermoDO = 3;
int thermoCS = 4;
int thermoCS2 = 5;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
MAX6675 thermocouple2(thermoCLK, thermoCS2, thermoDO);

void setup() {
  Serial.begin(9600);
  Serial.println("MAX6675 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp
  Serial.print("C = ");
  Serial.println(thermocouple.readCelsius());
  Serial.print("F = ");
  Serial.println(thermocouple.readFahrenheit());
  Serial.print("C 2= ");
  Serial.println(thermocouple2.readCelsius());
  Serial.print("F 2= ");
  Serial.println(thermocouple2.readFahrenheit());
  delay(1000);
}

I am able to read only one sensor information correctly. The other output is nan. Am I wiring the circuit wrong or is my code incorrect or both?


texts: Transmitting signal from a Photon Redboard to an Arduino Uno

texts:
I am doing a basic electronics course revolving around the Internet of Things*, and we have to make a final project to present what we have learnt.
* Hear me out - I don't think this belongs on IoT SE, since the question is electronics-based

My project involves lighting up an LED matrix with predefined input from the web.

There are three factors causing a problem for me:

The LED matrix only seems to work on an Arduino (even though the programming language and setup are very similar), and we only have Arduino Unos available to us.
We are required to use a Photon Redboard to receive/send data through the internet.
The code running the LED matrix interferes with the TX/RX terminals on the Arduino since it uses the SPI bus, so after turning on the LED board I cannot receive any data from the Photon Redboard through the TX/RX pins (0 and 1).

Main question (to avoid the XY problem):

How could I receive digital data on the Arduino Uno from the Photon Redboard without using the serial ports?

What I have done to try to fix the problem:

Google-fu didn't turn up anything.
Changing the location of serial use in the programming - it works before the SPI bus is initialised but not after, which is useless for me since changing the board in response to an input from the Photon Redboard is the point of my project, and I can't change the board if it's not on.
Connecting a digital port programmed for output on the Photon Redboard to a digital port programmed for input on the Arduino Uno — this gives a value on the Arduino Uno that seems to switch between HIGH and LOW every few seconds, regardless of how the Photon Redboard is programmed to send values.

Subquestion(s):

If I am connecting the boards as described above, do I need to ground/insert current into the connection, and if so, is there a particular board this needs to be done on?

(Out of curiosity, also, what is causing the value to flip like this?)

Checking the components individually - the LED matrix works fine by itself, serial over TX and RX works fine by itself, the digital pins work fine by themselves (NB: tests were carried out with an LED or a button to provide visual feedback).

Here are pictures of both the Photon Redboard and the Arduino Uno for reference (click on images for better resolution, Arduino just shows circuitry without chips etc.):

Sources: Sparkfun and Arduino main websites

The code that seems to interfere with the Serial is below (directly copied from online here):

//----------SPI BUS SETUP----------
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR1);  //Enable SPI HW, Master Mode, divide clock by 16

//Set the pin modes for the RGB matrix
pinMode(DATAOUT, OUTPUT);
pinMode(DATAIN, INPUT);
pinMode(SPICLOCK,OUTPUT);
pinMode(SLAVESELECT,OUTPUT);

//Make sure the RGB matrix is deactivated
digitalWrite(SLAVESELECT,HIGH);
//----------END SPI BUS SETUP----------

The four lines of pinMode(PIN,I/O) refer to pins 10-13 (in standard SPI order, but I can't remember what order that is and I don't have access to the code).


texts: Piezo connection causing RTC to go haywire


texts: Change max and min read value of potentiometer

texts: I'd like to know if there is a function or some way to define min and max value to potentiometer, for example: I'm using a mechanical part that only tour the potentiometer a little bit, what means the potentiometer doesn't start in the beginning and doesn't finish in the end. So, how can I make this space the potentiometer tour means 0 to 255 the start to end, respectively?


texts: Can I measure velocity from an accelerometer? How accurately?

texts:
I've bought this module

Kootek GY-521 MPU-6050 MPU6050 Module 3 Axis analog gyro sensors+ 3 Axis Accelerometer Module

My project will involve affixing this to a moving object, moving at velocities varying from 0.1 to 1.0 meters per second.

From what I understand, this module will allow me to infer rotation and acceleration, will I be able to derive velocity?

How much accuracy can I expect?


texts: Arduino Nano, Uno and Mega - XBee connection difference

texts:
I have a simple sketch working on arduino Uno and Nano sending data using an XBee.
However, if I run the project on an Arduino Mega it does not work.

What differences between Uno/Nano and the Mega could be causing issues?

Connection:  I just connect 3.3V->3.3V, Gnd->Gnd, and have tried various ports for DIN and DOUT (normally pins 2/4, but have tried A0/A1, 22/23 etc..).

Sketch: pastebin

Have brought a second Mega in case of hardware faults, but the problem persists.  Have stripped anything which might be tying up a timer.  Am choosing the right board type in the arduino IDE.


texts: How can i call lcd.begin() from several different code files in a proper way?

texts:
I have a project split into several files:
//Loop.cpp
#include "LiquidCrystal.h"

void setup(){
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    lcd.begin(16, 2);
}

void loop() {
//Code
}

//Display.cpp
#include "LiquidCrystal.h"

namespace display {
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void displayData(const InputPacket &inputPacket, const DataPacket &dataPacket) {
    lcd.setCursor(0,1);
    lcd.print("Foo");    //This creates display error, unless i call lcd.begin(16, 2) in this function
}

} //namespace display

My initial problem is that - without calling lcd.begin() from within displayData() - the characters aren't displayed correctly. In other words, calling lcd.begin() in setup() doesn't help. (It appears to me that setup() has implicit static property, no?)
As an attempted solution, i could create an lcd object in Display.cpp, and call lcd.begin() from within displayData(). Even though characters are displayed properly, this gives me display flickering. (Presumably as a result of calling these functions repeatedly in the loop during runtime).
So, the only solution to this dilemma that i can come up with is to call lcd.begin() from a function written to run only once inside of displayData(). Or is it?
My question is, are there other more elegant solutions/alternatives?


texts: Difficult between atmega328 & atmega2560 when coding & compiling in a pure c

texts:
I have an arduino uno with atmega328p controller.

I found the code to deal with some specific uart protocol, named mdb: https://github.com/Bouni/MateDealer/tree/master/arduino

But it's compiled just for atmega2560 controller: https://github.com/Bouni/MateDealer/blob/master/arduino/makefile#L42

If I replace it by atmega328p or atmega328, I get the error:

asiniy@misha:~/projects/MateDealer/arduino$ make all

-------- begin --------
avr-gcc (GCC) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Compiling: main.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/main.o.d main.c -o main.o

Compiling: usart.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=usart.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/usart.o.d usart.c -o usart.o
usart.c:25:40: error: ‘UBRR1H’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                        ^
usart.c:25:49: error: ‘UBRR1L’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                 ^
usart.c:25:58: error: ‘UCSR1B’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                          ^
usart.c:25:67: error: ‘UCSR1C’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                                   ^
In file included from usart.c:14:0:
usart.c: In function ‘USART0_RX_vect’:
usart.c:185:5: warning: ‘USART0_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_RX_vect){
     ^
usart.c: In function ‘USART1_RX_vect’:
usart.c:197:5: warning: ‘USART1_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_RX_vect){
     ^
usart.c:203:12: error: ‘UDR1’ undeclared (first use in this function)
     data = UDR1;
            ^
usart.c:203:12: note: each undeclared identifier is reported only once for each function it appears in
In file included from usart.c:14:0:
usart.c: In function ‘USART0_UDRE_vect’:
usart.c:233:5: warning: ‘USART0_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_UDRE_vect){
     ^
usart.c: In function ‘USART1_UDRE_vect’:
usart.c:253:5: warning: ‘USART1_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_UDRE_vect){
     ^
usart.c:261:31: error: ‘TXB81’ undeclared (first use in this function)
                 UCSR1B |= (1<<TXB81);
                               ^
usart.c:266:9: error: ‘UDR1’ undeclared (first use in this function)
         UDR1 = data;
         ^
usart.c:269:20: error: ‘UDRIE1’ undeclared (first use in this function)
     UCSR1B &= ~(1<<UDRIE1);
                    ^
make: *** [usart.o] Error 1

I've tried to play with compilers (default is gnu99) and so on, but with no success. Why I have this trouble? How can I compile this code for upload it to arduino?


texts: communicating with arduino over serial via terminal

texts:
I'm attempting to write data over a serial line to the arduino, however I don't want to use the arduino IDE but rather use the command line.

In order to do this I have the following commands:

$stty -F /dev/ttyACM0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
$echo s123 > /dev/ttyACM0

The code on the receiving end checks whatever or not the input is s123 and if it is starts blinking. I have tested this using the arduino IDE and it worked, however this did not work.

The sketch looks like this:

    void loop(){
     if(Serial.available()==4){
       byte b1,b2,b3,b4;
      b1=Serial.read();
      b2=Serial.read();
      b3=Serial.read();
      b4=Serial.read();
        if(b1=='s'){
               digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
               delay(1000);               // wait for a second
               digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
               delay(1000);               // wait for a second
               digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
               Serial.println("the cow has landed");
          }
     }

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

the output of

stty -F /dev/ttyACM0 -a

was :

speed 9600 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W;
lnext = ^V; flush = ^O; min = 0; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread clocal -crtscts
ignbrk -brkint -ignpar -parmrk inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon -iexten -echo -echoe -echok -echonl noflsh -xcase -tostop -echoprt -echoctl -echoke

Thank you


texts: Since I don't like the text editor of the Arduino IDE, I decided to write a python script that I can invoke from my text editor to compile and upload my source. I program the popular esp8266 chip. So far I found that there is a python builder here. This did not work for me. So is there any way to compile my source (e.g. main.ino) via a terminal command?


texts: Arduino program using i2c stops working after printing to OLED a few times

texts:
A NOTE ON THE PROJECT AND PROGRAM STRUCTURE

I am developing an open source Smart Watch project using Arduino.
The code can be found here: https://github.com/shivangsgangadia/SmartWatch
The code is too large and divided into multiple files, hence I cannot paste it here within the question, hence I request you to look into the github repo.

So far I have interfaced an OLED (128 X 64 SSD1306) and RTC (DS3231 in ZS-042).
I have written libraries for both, which have been included in Github repo.

The program structure allows to add multiple "Modules" which are basically like apps. There is a static State class that holds the program state such as modules to be serviced, and time from RTC.
Each "Module" can be a "App" or "Overlay". Overlays are always visibles, there can be mutiple overlays active, but only 1 app can exist at a time.

WHAT I AM TRYING TO DO ?

Read RTC into State class's static variables
Display once
Attach interrupt to set boolean flag when the RTC gives interrupt (alarm
set to 1 minute) Service interrupt in loop by:

Read RTC into State class's static variables
Reset alarm for RTC
Update display

WHAT IS THE PROBLEM ?

The program works fine 2-3 times, i.e. does what's expected after servicing 2-3 interrupts (hence 2-3 minutes), but after that the print on the OLED becomes mangled and the program stops altogether.

WHAT HAVE I TRIED TO SOLVE IT ?

With Serial.println() in many areas such as before and after OLED::writeString is called in respective classes, I concluded that the RTC is not the issue, but the OLED somehow causes the program to stop.

Removing OLED::writeString statements does allow the rest of the printing to continue for more than 2-3 times, but the program eventually does stop. I have tried replacing the wires and the breadboard, but nothing seems to have any effect.


texts: Cannot directly connect Arduino Ethernet to PC

texts:
I have been following various tutorials (especially: this) to connect an Arduino Ethernet board to my Ubuntu PC via Ethernet directly.

The IP address of the computer was found to be 10.100.31.128, and so I tried addresses in this range (10.100.31.67, 10.100.31.121, ...) without success. DHCP also doesnt seem to work. For the MAC address I used the sticker on the back of the board. I am using a patch cable, maybe that's the problem?


texts: Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V?

texts:
To control my robot, I need to generate negative and positive voltage in a single line, because the motor I try to control is an industrial one.

Do you have any suggestion for it? How can I produce a negative voltage using an Arduino board and simple electrical elements?


texts: Can I run two function in arduino simultaneously?

texts: I'm new to arduino world and I don't have any background. I just want to ask if I can run two function in arduino simultaneously. I'm going to make an earthquake detector but at the same time, I want to receive an sms to my phone when its alarm. Is this possible?