texts: Can I use this power supply with my Arduino?

texts:
I am new to Arduino and electronics in general.

I am working on a project where I would ultimately like to power the project from 220V AC (Wall light switch) (I want to replace the light switch with one of my own design).

I will want to feed power to the arduino directly from the 220V connecting wires in the light switch cavity.

This power source is 5V (I know the Arduino needs 9-12V), but I will use a USB connector, wired onto my AC/DC power source, to power the Arduino.

Power Source

Ratings:

AC85 - 264V or  DC110 - 370V wide voltage input
DC 5V(+/ -0.2V) 600mA isolated output
Input Current: 0.0273A/115VAC  0.014A/230VAC
Input surge current: 20A (230VAC)
Frequency range: 50/60 Hz
Operating Temperature: -30 - 70 ℃
Relative humidity: 20%- 90%
Rated power: 3W
Output efficiency: 80%

I don't really know why yet (this is part of figuring that out), but I have the feeling that the arduino would want a linear power source, rather than a switching power source. (Because linear is cleaner power?)

Regardless, I am asking the question as if this power source will do the job, and if not, why not? (Why not a switching PSU) ?


texts: Arduino HTTP Request Fails Slow Cellular Connection

texts:
Setup:

Arduino Mega 2560 w/ Wiznet W5500 Ethernet Sheild
Using TP-Link TL-MR6400 LTE router to connect to internet over cellular connection in Uganda.

Using an HTTP Post with the following,

client.println("POST /hook HTTP/1.1");
client.print("Host: "); client.println(server);
client.println("Accept: */*");
client.print("Content-Type: text/html;");
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);

where PostData is a String and Ethernet2 is the library used.

This works just fine from the US to the same AWS server, or a https://requestbin.com/ instance.

When testing from Uganda using a Raspberry Pi and curl it works fine.

$ curl -vs -d 'ABCDEFG' -H "User-Agent: Arduino/1.0"  -H "Content-Type: text/html" -H "Connection: close"   http://<server here>/hook
*   Trying <ip here>...
* TCP_NODELAY set
* Connected to <server here> (<ip here>) port 80 (#0)
> POST /tg HTTP/1.1
> Host: <server here>
> Accept: */*
> User-Agent: Arduino/1.0
> Content-Type: text/html
> Connection: close
> Content-Length: 7
>
* upload completely sent off: 7 out of 7 bytes
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Content-Type: application/json; charset=utf-8
< Date: Tue, 06 Aug 2019 21:06:49 GMT
< x-pd-status: sent to primary
< X-Powered-By: Express
< Content-Length: 16
< Connection: Close
<
* Curl_http_done: called premature == 0
* Closing connection 0
{"success":true}

I even tried an HTTP GET example from the Ethernet2 library,

https://www.arduino.cc/en/Tutorial/WebClientRepeating

It worked just fine in the US but in Uganda I get,

My IP address: 192.168.1.177

connecting...

connecting...

connecting...

I increased the time between requests here to 100 seconds where it is listening for the whole time inbetween.

It seems that client.connect(server, 80) is successful and the client.print messages go through but the message never reaches the server so there is no response. My AWS server does not recieve the request and this is the same for the requestbin instance. This behavior is mirrored in all my Arduino tests.

I thought the ISP might be blocking but the RPi can send nearly the same message. I thought maybe a timeout somewhere but I can not find where with my tests. I thought my message was too long but I reduced the size to only 10 characters with the same results.

Trying to figure out why the Arduino HTTP request cannot reach any webhooks from Uganda and how to fix it if possible. Different ISP, slower connection, cellular connection?

Any help would be appreciated.


texts:
I want to build a line follower car, but I dont have Infrared sensors, so want to run the car, without sensors as a test

I have Motor Driver on top of Arduino UNO R3, all connections as expected, but all wheels are not spinning. I have no idea on which one is Motor1, 2,...

Code: https://create.arduino.cc/projecthub/adamsstephen/controlling-an-l9100-motor-driver-board-using-arduino-cc5618#toc-step-1--placing-electronics-0

int Motor[8] ; // Array for all Motor Output pins, one more than required

void setup() {
  Motor[1] = 4; // Set output numbers for ports
  Motor[2] = 5;
  Motor[3] = 6;
  Motor[4] = 7;
  Motor[5] = 8;
  Motor[6] = 9; // Set up Port for LED on Head of Arm.
  Motor[7] = 10; // Forward / Reverse selection for ALL motors
  // Switch connected to GND and A0, to locally turn off motors while testing.
  pinMode(Motor[1], OUTPUT); // Open Port to operate Motor on Pincers Forward = In Reverse = Out
  pinMode(Motor[2], OUTPUT); // Open Port to operate Motor Up= High  Reverse = Down
  pinMode(Motor[3], OUTPUT); // Open Port to operate Motor Forward = Forward Reverse = Backward
  pinMode(Motor[4], OUTPUT); // Open Port to operate Motor Wrist Forward = Up Reverse = Down
  pinMode(Motor[5], OUTPUT); // Open Port to operate Motor base Rotate Forward = Right Reverse = Left
  pinMode(Motor[6], OUTPUT); // Open Port to operate LED on head of Arm HIGH = ON LOW = OFF
  pinMode(Motor[7], OUTPUT); // Open Port for Forward / Reverse selection for ALL motors
}
void loop() {
    digitalWrite(Motor[6], LOW); // Turn off LED.
    if (analogRead(A0)< 1){ // switch ON
    digitalWrite(Motor[1], HIGH); // Turn on Motor 1. HIGH turns it on! Pincers
    digitalWrite(Motor[7], LOW); // HIGH is Forward, Reverse is OFF.
   Serial.println(analogRead(A0));
}
    if (analogRead(A0) > 200  ){    // switch OFF
    digitalWrite(Motor[1], LOW); // Turn on Motor 1. HIGH turns it on!
    digitalWrite(Motor[7], LOW); // HIGH is Forward, Reverse is OFF.
   Serial.println(analogRead(A0));
}
    delay(200); // debounce the switch action
}

I commented the whole loop(), still some wheels are spinning. how is that possible? How can I know - which one is Motor1 ,...M4 and the corresponding Arduino pin numbers.
I want to spin all 4 wheels/ dc motors


texts: ESP8266WebServer how to parse Json payload in post request that is bigger than the ram

texts:
I need to post a big json to the nodemcu server which would be bigger than the ram's size

I am using esp8266werserver and arduinojson libraries. I know how to use arduinojson to parse huge json response from other servers by parsing the response as a stream using response.getstream() . I can reuse a small static buffer in the stack to parse the whole json in a loop which performs really well.

But when I use nodemcu as a server, I can't find any similar method in the ESP8266WebServer to allow me to process json response as a stream. All I can only do is to read the string file in server.arg("plain") which may crash as the string may get bigger than the ram.

Is there a quick and dirty workaround? I look at the source in parsing.cpp there is a readBytesWithTimeout method that seems to be responsible to actually parsing the response stream. I am wondering if I may override this function to do what I need but I don't know how.

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/src/Parsing.cpp


texts: How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?

texts: I am working on Fall Detection in humans. A system that would raise alarm when a person falls. For this I plan to use acceleration to see if it is a fall and orientation change to reduce false positives. I was trying to get angle of orientation using gyroscope,accelerometer and magnetometer. According to what I have googled I shouldn't use gyroscope alone as when we integrate to get angle the result is not accurate and I should use sensor fusion and filter using kalman filter or complementary filter. I can't use accelerometer  as during a fall the acceleration won't be only from gravity. I am a newbie so I don't know how to proceed. Correct me if I have understood anything wrong till now.


texts: How to prevent flickering relay upon waking from deep sleep using ESP01 board?

texts:
I have a cheap ESP01 relay module and am using it with ESPEasy. I soldered the GPIO pin 16 to RST to allow deep sleep and that all works great.
However when the unit wakes up the relay flickers quite a bit. The application I had in mind was for a 12v fridge which draws quite a bit of current on start up. I think this flickering would damage the fridge compressor or controller pretty quickly, not to mention wearing out the relay itself.
I need the unit to wake up from deep sleep, and keep the relay in the off position, unless triggered by some external criteria.
Perhaps a capacitor would absorb the pin high voltage for a short period until it's booted? Trouble is that I don't really want to hack the module, I'll probably break something.


texts:
I want to create arduino sketch that start program on my computer (i.e., browser) when I push button on Arduino itself.

Is it possible to make it using Arduino uno? I already know how to make a serial connection between PC and Arduino and use Processing software, but as I know, Processing cannot interact with another programs.


texts: How can I connect multiple MCP23017's to an arduino?

texts: I am working on a project and I am trying to figure out how to connect multiple MCP23017 IO Expanders to one arduino. All of the guides that I have found in my quest for information only explain how to connect one MCP chip or how to address multiple MCP chips. None seem to explain how to connect them physically. BTW, I am talking about the I2C version of the chip.


texts:
I bought an arduino compatible board here: http://unsigned.io/projects/micromodem/
and am trying to flash new supported firmware onto it. The only instructions given to flash the board is to use the command avrdude -p m328p -c arduino -P /dev/ttyUSB0 -b 115200 -F -U flash:w:YourFirmwareFile.hex .

I'm trying to follow the tutorial here using an Uno as a programmer: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader#uploading-code---hard-way but I don't know what to use for the fuse settings. I've tried a few different fuse settings such as the one for the Uno, and default 328p ones using a fuse calculator but it seems like they all have unpredictable results. Some fuse settings make it so that I can't connect  to the COM port at all to monitor the traffic, and others let me connect, but send a message of . I'm expecting an introduction message from the firmware that is supposed to be built in.

Thanks for the help.


texts:
I have two arduinos (one uno and another nano) with NRF24L0 modules attached to both and they are communicating between each other. All good.

However, I have a load of different ones and have switched them with the working receivers to test them but they just refuse to work despite the pinouts being correct.

Does the pinout vary between manufacturers or something else perhaps? What really perplexes me is that some of the modules I've tried are brand new (just taken out of the antistatic)

I have followed https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/

Any help would be really appriciated. Thanks


texts: sending 16 bit command via SPI to a NCV7719 (half bridge)

texts:
I am trying to send a 16 bit command to a Half bridge (data sheet here http://www.onsemi.com/pub/Collateral/NCV7719-D.PDF) to open one of the transistors to turn on an LED. at the bottom of the data sheet (page 13) it says which bit needs to be a 1 or a 0 in order to activate the half bridge. This is the code I wrote but it isn't work (I'm assuming I'm not sending the 16 bits properly). Can someone figure out why this isn't working?

#include <SPI.h>

void setup() {
  // put your setup code here, to run once:
  pinMode(10,OUTPUT);
  pinMode(8,OUTPUT);
  digitalWrite(8,HIGH);
  SPI.begin();

}

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

  //pulling pin low to decide to write to device
  digitalWrite(10,LOW);

  //function to send information
  //truning on half bridge 4
  SPI.transfer(0000010000000000);
delay(500);
  //finish transfering data
  digitalWrite(10,HIGH);

}


texts: How does supply voltage affect `analogRead()` on AVR-based microcontrollers?

texts:
I'm using an ATmega328P based Arduino to prototype reading a TMP36 temperature sensor. I will eventually move this to an ATtiny85 based board with a battery supply. Both the TMP36 and ATtiny85 have a Vcc range from 2.7V to 5.5V so a battery that starts at say 4.5V and slowly drops to 2.7V should not be out of range.
I am expecting to read temperatures in the range -5°C to +30°C which should correspond to a TMP36 output between 0.5 to 0.9V. I am getting 0.74V at around 23°C so this sort of range seems plausible.
The TMP36 outputs 10 mV/°C regardless of Vcc (within 2.7-5.5v). But I suspect the AnalogRead() value will be scaled by the supply voltage and so will slowly change as the battery drains. Is this correct?
Do I need to include an external voltage-regulator / voltage-reference device to supply some fixed voltage (e.g. 2.5V) to AREF?

Solution
Following Edgar Bonet's Answer I successfully enabled the internal voltage reference for the ADC.
Initially I added a 100nF bypass capacitor to AREF and tried
#define REFS1 7
#define REFS0 6
#define REFS2 4

...
//ADMUX = (_BV(REFS1) | _BV(REFS2)); // 2.56V ATtiny85   datasheet §17.3 pp134
ADMUX = (_BV(REFS1) | _BV(REFS0)); // 1.1V  ATmega328P datasheet §23.9 pp217

but didn't get it to work, my code had no effect on values from analogRead(). So after a bit of further reading I instead used
analogReference(INTERNAL);

Which worked.


texts:
using this code to try and play a random song when someone walks by my distance sensor I get an error, the same song(track 0001)  plays every time. Any advice?

#include <SoftwareSerial.h>
SoftwareSerial Geno(7,8); // Rx , Tx

unsigned char Data[10];
unsigned char i;

// defines pins numbers
const int trigPin = 8;
const int echoPin = 9;

// defines variables
long duration;
int distance;

void setup() {
  delay(1000);
  Geno.begin(9600);
  delay(1000);
  SetVolume(30);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void playTrack(int num){

    delay(100);

    Data[0] = 0x7E;
    Data[1] = 0x04;
    Data[2] = 0xA0;
    Data[3] = 0x00;
    Data[4] = 0x00 + num;
    Data[5] = 0x7E;
   Command(Data,5);

    play_pause();

    delay(10000);

}

void SetVolume( int vol){
   Data[0] = 0x7E;          // START
   Data[1] = 0x03;          // Length Not 0x02
   Data[2] = 0xA7;          // Command
   Data[3] = vol;          // new volume
   Data[4] = 0x7E;          // END
   Command(Data,5);
}

void play_pause(){
  Data[0] = 0x7E;          // START
  Data[1] = 0x02;          // Length
  Data[2] = 0xA3;          // Command
  Data[3] = 0x7E;          //Mode parameter
  Command(Data,4);
}

void Command(unsigned char *Data, int length){
    for(int i=0; i<length; i++){
    Geno.write(Data[i]);
    }

    }

void loop() {
  //Assigns a random number
  int song = random(0,200);
  Serial.print("Song is:");
  Serial.print(song);
  Serial.print("\n");
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance= duration*0.034/2;

  Serial.print("Distance: ");
  Serial.println(distance);
  if(distance < 20){
    playTrack(random(1,25));
  }
  //playTrack(1);
  //playTrack(2);
}


texts: How to prepare data structures and classes?

texts:
How can I port these structures to arduino ide, I also get error when I define pointers

// pointer to classes example
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';
  delete bar;
  delete[] baz;
  return 0;
}

In CPP shell it works

I try to put it like this

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };

void setup() {
  // put your setup code here, to run once:

}

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

}

I get an error

sketch_nov27a.ino:10:3: error: 'foo' does not name a type
sketch_nov27a.ino:11:3: error: 'bar' does not name a type
sketch_nov27a.ino:12:3: error: 'baz' does not name a type
Error compiling.


texts:
I am trying to make an Arduino project based on the Sparkfun DS1307 RTC (real-time clock).

There are a few issues with how Arduino libraries don't support checking if the Arduino board has been powered down and check for that.

Then using that as a conditional as to when the program should fall back to the compiled time if the RTC isn't set to a time yet because of something else.

When I power down the clock, it will automatic fall back to the compiled time every single time, regardless of what is currently on the RTC. Clearly this is not something you would want.

Edited - This is my current code. Keep in mind there are a few more changes I could do like take Byte zero declare out of the loop so it is still rough.

#include <Wire.h>
#include <SparkFunDS1307RTC.h>

#define DS1307_ADDRESS 0x68

void setup() {
  Wire.begin();
  Serial.begin(9600);
  rtc.begin();
  if(false){
    //Should check RTC somehow to determine if should fallback to compiled time here.
    Serial.println("The DS1307 clock has lost power and reset to compiler's time");
    rtc.autoTime();
  }
}

void loop() {
  if(digitalRead(7)==LOW)
    printDate();
  delay(1000);
}

byte bcdToDec(byte val){
  return ((val/16*10) + (val%16));
}

void printDate(){
  rtc.update();
  Wire.beginTransmission(DS1307_ADDRESS);
  byte zero = 0x00;
  Wire.write(zero);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_ADDRESS, 7);
  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  int weekDay = bcdToDec(Wire.read()); //0-6 -> Sunday - Saturday
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  //Print the date like 3/1/1/11 23:59:59
  Serial.print(month);
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}


texts: Managing 80 ~ 90 accelerometers with Arduino

texts: If one were to want to keep track of data from 80 - 90 accelerometers using arduino, what would be the best way to go about this challenge?


texts: Does lowering arduino analog reference increase precision in measuring low voltage?

texts:
The definition for Analog Reference is as follows: The reference voltage used for analog input (i.e. the value used as the top of the input range).

By default you have analog reference of 5V. So the precision of analogRead is 5 / 1023 = 0.0048875.

Now what happens if I lower the analog reference to let's say 1V. Does that mean that the precision now is 1 / 1023 (and the arduino can't measure voltages higher than 1V) or it is the same precision as before with the only difference being the fact that the arduino can't measure voltages higher than 1V anymore?


texts: What kind of distance sensor are optimal to measure distances to surfaces at an angle to the sensor?

texts:
I want to try measuring the orientation of an object by measuring the distance between a "flat" surface to the surface of the rotated object. The problem I assume is that if the surface being measured is at an angle to the distance sensors, the beamed lights from laser or infrared proximity sensors, for example, would be reflected at an angle and not return to the sensors at all.

Would this actually happen, or am I misunderstanding some properties of these sensors? Which sensors would work in this kind of application, and which sensors would not work for sure (I read from another post that ultrasonic sensors would definitely not work in this case)?
(Added a crude sketch of the problem I think is going to happen)


texts: Can I connect a remote control relay to a arduino uno board by disabling the remote control in the relay?

texts: I was making a home automation system by making some of the appliances in the home like fans and lights voice activated. But by mistake I bought a remote controlled relay in place of a normal relay from a shop and return does not seems possible. So I want to know if I will be able to use that remote controlled relay in this project?


texts:
I'm using an Adafruit NRF8001 Low Energy Bluetooth module and a Real Time Clock module with my Arduino board. I want to connect to the BLE module using UART to set the clock. I'll also be using UART to set alarms.

I'm not sure which is the best way to take a string from the UART receiver and pull it apart into the hours, minutes, second, etc.

Any ideas? I did look at the Arduino JSON library but it seems a little buggy, and possibly overkill.

Any help would be very much appreciated :)


texts:
I'm working on water level detector using lolin nodemcu v3 and AJ-SR04M Sensor, a water proof ultrasonic sensor. It is working fine at close distance less than one meter or so. However for long distance > 1 meter, I get varying results.

Using the following code:

void setup() {

  Serial.begin (115200);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
}

void loop() {

  long duration, distance;
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(2);

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

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

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(1000);
}

This is what I get in the monitor for the same distance 2-3 meters:

Distance: 141 cm
Distance: 135 cm
Distance: 225 cm
Distance: 195 cm
Distance: 226 cm
Distance: 226 cm
Distance: 129 cm
Distance: 135 cm
Distance: 134 cm
Distance: 146 cm
Distance: 136 cm
Distance: 129 cm
Distance: 154 cm
Distance: 123 cm
Distance: 147 cm
Distance: 226 cm
Distance: 181 cm
Distance: 137 cm
Distance: 134 cm
Distance: 136 cm
Distance: 137 cm
Distance: 145 cm
Distance: 227 cm
Distance: 179 cm
Distance: 226 cm
Distance: 226 cm
Distance: 101 cm
Distance: 134 cm
Distance: 270 cm
Distance: 294 cm
Distance: 266 cm
Distance: 281 cm
Distance: 146 cm
Distance: 279 cm
Distance: 128 cm
Distance: 579 cm
Distance: 138 cm

So, is there a way to make it right or that means my sensor is faulty.


texts:
I found this pump:

https://www.aliexpress.com/item/Free-Shipping-Ultra-quiet-DC-12V-3M-240L-H-Brushless-Submersible-Water-Pump-High-Qualtiy-mini/32472119699.html

Now, I want to control it from an Arduino.

Is this a good relay to use?

https://www.pololu.com/product/2480?

I want to use a 12v battery for the pump.


texts:
I want to modify (extend) g_APinDescription array defined in the variant.cpp.
It is necessary for new pin addition. I want to use PB0-PB7 ports as an external interrupts.

I tried the following code:

g_APinDescription = (const PinDescription *) realloc(g_APinDescription, (103 * sizeof(const PinDescription)));

I have a compilation errors:

  invalid use of array with unspecified bounds

I'm not C expert and don't know what is wrong here.

I want to use several pins which are unconnected on the DUE.
Usual read and write is simple to implement but if I want to use the interrupts then difficulties arrive.


texts: Default value of global variables is not set

texts:
I am tracking a bug in the Marlin source code.

Background

Just for those who is not familiar with Reprap 3D printer and G-code: Marlin is firmware that controls a RepRap 3D printer. It receives G-code from a host computer (or read from SD card). Here the important thing is that if you send the "M114" command, it would report information about axis positions. Here, I extended this command to make it print some internal variable as well.

The Problem

In Marlin.ino file there is a line that says:

volatile int extrudemultiply=100; //100->1 200->2

However my RepRap keeps extruding (and worse, ejecting back) a huge amount of filament. So I added some debug output for M114 command to output this value. It turns out this value is not the default value, 100, but something like 12374.

I thought somewhere inside the setup() function this value might be changed. So I defined another variable,

volatile int orig_extrudemultiply = 100;

And then at the first line of setup() function, I added the following line.

orig_extrudemultiply = extrudemultiply;

Finally, I output this value for the M114 command. Still, it is not 100. So it looks like the default value is not effective.

The Question

Although I have experience in C programming, I am new to Arduino development. How is a global variable being initialized in Arduino? In my case, what is the proper way to initialize this value?

Versioning

I originally posted the official Marlin link for the reference. However,
the version I actually use is this fork from the RepRap Pro team. I was just following the Melzi entry of the RepRap wiki, because my board is Melzi. I am not sure whether the latest version of Marlin works for my board.

Further details

As the commenter said, the first thing I thought of was memory corruption. So I wanted to narrow the problem down. Since that value is configurable through M302 SXXX command, I tested this command, and it works without difficulty. This means there is nothing in the loop function or the ISRs can affect this value when it is running stably. So I consider the problem must be in the setup function or earlier.

Further tests shows that setting this value at the end of setup or even at the beginning of setup still works fine. This means the setup function may not be the problematic one. The test in "The Problem" session was the last step, which, in my opinion, means the course of the problem must being run before entering setup.

UPDATE

Further examination shows that although it looks like it works when I set the default value in the first line of setup(), but that it is just luckily being 100. So once I add more padding variables it stops working until I move the default setting after the following line in setup():

EEPROM_RetrieveSettings(); // Loads data from EEPROM if available

However, since I greped for extrudemultiply before any test, and I didn't figure out this function, this function should not change this value. I guess there is some data overflow inside this function, so the value was changed expectationally.

I got to figure out what is wrong in this function.


texts: Lithium Polymer/LiPo set to power Arduinos

texts:
I want to switch from using disposable 9V blocks to a proper setup of 3.7V LiPolys for all my portable Arduino (Uno/Mega) projects consisting of:

only 3.7V LiPo units
charger
upconverter (to 5V)

My questions:

Is this generally a good idea? Or is there a better solution for portable Arduino power?
How should I actually hook the LiPolys up to the Arduino? They usually ship with JST connectors. Should I use the Vin/GND Pins or should I build my own JST/DC-Connector adaptor? I want to create a robust, pluggable solution.
Am I actually losing power twice that way (once in the upconverter and then in the Arduino voltage regulator)?


texts: NodeMCU run sensor code while listening for wifi input?

texts:
Is it possible to have code running while also listening for local inputs via ip address? I thought it would go in the 'while' portion but I presume that only responses when the ip is loaded.

void loop() {

  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while (!client.available()) {
    delay(1);
  }
  String query = client.readStringUntil('\r');
  client.flush();

  if (query.indexOf("/open") != -1)  {
    open_fast();
  } else if (query.indexOf("/close") != -1)  {
    close_fast();
  }

  sensor = analogRead(A0);
  sensor = map(sensor, 0, 1023, 0, full);

  Serial.print(sensor);
  Serial.print("  ");
  Serial.println(pos);

  if (sensor > pos) {
    open_slow();
    delay(1000);
  } else if (sensor < pos) {
    close_slow();
    delay(1000);
  }
  delay(100);

}


texts: Do I have a faulty arduino uno, or have I found an Arduino bug?

texts:
Lately, we got an old arduino uno donated from a friend and have been trying to get it to work with servos. We have been having very perplexing results. We have tried many different "stock" code and servo combinations with our servos, but here is the behavior:

180 Servos automatically move to right max as soon as power is applied.
Sail Winch servo moves a tiny amount and then stops. If power wire is removed and then reapplied, the servo moves another tiny amount.

The code is very simple. First we call the servo.attach(pin), and confirm the pin. We have also tried doing the manual uSec definition: servo.attach(pin, 600, 2400). In our loop() we have tried servo.write(*value from 0-180*) and servo.writeMicroseconds(*value in PWM range*)

Power is being supplied by a 9v battery, the sensor (yellow) is directly in digital pwm pin, while red (power) is in + and black (ground) is in -.

I'm trying to decide whether I should invest in another arduino system.

servos:

180 servos

Sail Winch servo


texts: Sending a string from RPi to Arduino - Working Code

texts:
I've been researching for 2 days now trying to figure out how to receive a string via I2C on an Arduino. There are plenty of questions online but no real solutions or full tutorials... and sadly I threw my C++ book out years ago.

The code below compiles without error and receives the string correctly. (There are several commented out blocks that I've used to verify the data is being received.) The issue is printing the full received command string. I am unable to make it print in receiveEvent() or in the loop(). Ultimately I need it as a string such as "WIN-23-200" where I will explode the string by "-" to do something but I still can't get a hold of it.

If anyone can give me a nod in the right direction I'd appreciate it.

Thanks!

#include <Wire.h>

#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);

  Serial.begin(9600);
  Serial.println("Ready!");

}

void loop() {
  delay(1000);
  if (receiveFlag == true) {
    Serial.println("inFlag");
    Serial.println(command);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {
  //works as expected
  /*while (0 < Wire.available()) { // loop through all
    char c = Wire.read();
    Serial.print(c);
    }*/

  int count = 0;
  while (0 < Wire.available()) { // loop through all
    temp[count] = Wire.read();
    count++;
  }
  //temp[32-1]='\0'; //make sure its 0 terminated, didn't matter
  command = temp; //put char array into a string variable named command

  Serial.print(temp); // prints nothing....

  //Verify Array is Loaded..works great.
  //for (int i = 0; i < count; i++)
  //{
  //  Serial.println(temp[i]);
  //}
  receiveFlag = true;
}


texts:
So I am trying to work on a mini battle bot project. However, it has been a while since I have worked with my Arduino electronics. So I am going through and learning how to do each thing before putting it all together. So far I have learned how to use the IR remote and got that working. I got my brushless motor with esc working with the Arduino. Now I am trying to get my dc motors working for the wheel component. I am just trying to get one motor running from the motor shield as proof of concept essentially. So here is the run down.

I have 8xAA batteries in  series with each AA running at 1.5 volts for a total of 12 volts. I have verified this with my multimeter. The dc motors need 9-18 volts to run, so 12 should have it running. However, I will probably step that up to 18 volts for maximum power and run 4 dc motors since I am guessing my project will be a little heavy, so I need as much power as possible. I have the 8xAA batteries connected correctly with positive to the positive and negative to negative on the motor shield. I have checked my soldering connection and the pins are not bent and it looks straight and good. I made sure I firmly pressed down to get it onto the Arduino. Motor is connected to m2 as per the code. I don't understand why this isn't working as it should work. I have tried using this form: Why is my Adafruit motor shield not spinning my motors?

And that did not solve it. I originally was using a 9 volt battery but that form told me to use more than 9 volts and to use AA batteries, so I did that. I also checked my connections and made sure soldering is good. Here is my code:

#include <AFMotor.h>

// DC motor on M2
AF_DCMotor motor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor party!");

  // turn on motor #2
  motor.setSpeed(200);
  motor.run(RELEASE);
}

int i;

// Test the DC motor
void loop() {
  motor.run(FORWARD);
}

I have connected my motor to the battery directly and motor runs just fine. I have checked the voltage of my battery and it is great, not below the 12 volts and not above 13 volts. I have opened up serial monitor and I do see 'motor party' so I know the code is running. I looked for errors down below and saw none. The port I have checked and it is correct. Motor shield is made by Adafruit. I do have the correct library installed, in fact I just installed it today so I have up to date library. The lights on the Arduino light up and the light indicating power on the motor shield also light up when my AA batteries are plugged in. When I plug it in, lights light up but motor doesn't run. Here are a few pictures.

https://imgur.com/a/lzXDQmO

I am have a hard time figuring this out, so if anyone can help me, thanks in advance.


texts:
I am running Ubuntu Mate 16.04 LTS, with an Arduino Uno R3 clone. I am having the dreaded serial port graying out problem, and have not found a solution for fixing it. Currently, The serial port will grey out sometimes, and sometimes it will be not grayed out, and I can see that I have selected ttyUSB0. Usually when it is not grayed out, uploading a sketch will not work, and I get the error like it is grayed out:

  avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
  An error occurred while uploading the sketch

chmod a+rw /dev/ttyUSB0

doesn't solve the issue, with log out included

gpasswd -a aaron dialout

doesn't solve the issue, with log out included

I searched preferences.txt and serial.debug rate is set to 9600

I have tried entering preferences.txt and deleting all of the serial entries. They are recreated the same after deletion, and this doesn't solve anything.

I tried running as sudo, doesn't work.

I tried solving this originally on Arduino IDE 1.0, didn't work.

I have upgraded to Arduino IDE 1.6.10, still not working.

running lsusb in terminal yields this while Arduino is plugged in:

Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0a5c:21e6 Broadcom Corp. BCM20702 Bluetooth 4.0 [ThinkPad]
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Checking var/log/syslog after plugging in Arduino:

  kernel: [42043.787178] usb 3-2: new full-speed USB device number 109 using xhci_hcd

  kernel: [42043.916241] usb 3-2: New USB device found, idVendor=1a86, idProduct=7523

  kernel: [42043.916249] usb 3-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0

  kernel: [42043.916253] usb 3-2: Product: USB2.0-Serial

  kernel: [42043.916964] ch341 3-2:1.0: ch341-uart converter detected

  kernel: [42043.918199] usb 3-2: ch341-uart converter now attached to ttyUSB0

  mtp-probe: checking bus 3, device 109: "/sys/devices/pci0000:00/0000:00:14.0
  /usb3/3-2"

  mtp-probe: bus: 3, device: 109 was not an MTP device

Ran to add to dialout group, then logged out

sudo usermod -a -G dialout aaron

No solution.
So it looks like Arduino board is not being recognized. Not sure what to try next. It is important that I have uploaded sketches before, but am not sure if there is a pattern to when it does not work. It does not work 95% of the time.

Thanks for the help!


texts: reading pwm signal doesn't work correctly

texts:
my goal is to read a pwm signal from a rc receiver. For that i tried to use an arduino.

i ran this code on the arduino:

#define Pin 3

int pwm_value;

void setup() {
  pinMode(Pin, INPUT);
  Serial.begin(9700);
}

void loop() {
  pwm_value = pulseIn(Pin, HIGH);
  Serial.println(pwm_value);
}

Now i connected the 3rd pin with the output of the receiver. But instead of printing the correct pwm values they get printed completely crazy. Sometimes they are under 10 and sometimes they are over 10000. The receiver outputs the correct signal.

I also noticed that if i just touch the pin with my finger or if i only connect a single jumper cable without anything at the end, the arduino will read a pwm signal.

I have realy no idea to solve that. Can you please help me?

Thank you!


texts:
I have a problem in a project that I am working, basically I need to use a ESP-01 to receive the measurements from a HC-SR04 and send it to another ESP-01 (which I won't cover here).
Basically my ESP doesn't boot 95% of times, it just stays with the blue LED on all the time, on the remaining 5% of cases it boots normally and reads the sensor and also sends the information to another ESP.
I have done a lot of research and I am aware of these points:

HC-SR04 works in 5V and ESP in 3.3v, so a level convertor would be needed for the GPIO pins.  But, I have seen that the manufacturer (Espressif) stated that the ESP is resistant to 5V logic and it should work.  Also, I asked my professor and he said that it wouldn't be a problem.

Both IO pins need to be HIGH to boot, and the sensor seems to supply low, but like I said the ESP01 does boot, but not all the times.

That said, I would like to know why it works sometimes and others not, trying to get a little more of stability for presentation purposes...
Also it's worth noting that I have another ESP-01 connected with a DHT11 sensor with basically the same settings and it works normally.
The connections go like this:

ESP-01
HC-SR04

GPIO0
Trigger

GPIO2
Echo

GND
GND

Component
Power

ESP-01 Vcc, CH_PD
3.3v

HC-SR04 Vcc
5v

The code:
// pins of the esp8266 connected to the sensor
#define trigPin 0  //GPIO0
#define echoPin 2  //GPIO2

// intialize the variables for storing the measurement
float timeElapsed;
float distance;

void setup() {
  // Init Serial Monitor
  Serial.begin(115200);

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

}

void loop() {
  // do the measurements of the sensor
   digitalWrite(trigPin, LOW);  //para generar un pulso limpio ponemos a LOW 4us
   delayMicroseconds(4);

   digitalWrite(trigPin, HIGH);  //generamos Trigger (disparo) de 10us
   delayMicroseconds(10);
   digitalWrite(trigPin, LOW);

   timeElapsed = pulseIn(echoPin, HIGH);
   distance = timeElapsed/58.3;

   delay(1000);

  if ((millis() - lastTime) > timerDelay) {
     // code to send the information over wi-fi

  }
}

I have tried already:

Changing the ESP and HCSR04
Inverting GPIO0 and GPIO2
Boot without the sensor and connect it after, no succes
Different values in Arduino IDE during compilation of code

Thanks for your attention!


texts: How to change the usb name of Atmel 32u4?

texts:
I want to change my Arduino Leonardo's name that Windows shows me when it's plugged in.

I know that i have to change its firmware to change the name but I cant find firmware for it on the Internet.

On Arduino Mega, I have changed it with a downloaded firmware via flip, but I can't change the file because it's a .hex.


texts:
I'm planning to use an ESP8266 (Wemos D1 Mini) to use as a software SPI monitor to send over WiFi.
As a test, I've done a cut-down sketch that just counts the interrupts, a simple frequency counter. I've made it as simple as possible but it won't stay connected to WiFi and crashes after about 10 seconds.
The input signal to CLKPin is 6667Hz.
Here's the sketch:
#include <ESP8266WiFi.h>

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

long nextPrint = 1000; // when to print the next message to serial

const int CLKPin = 5; // Pin connected to CLK
volatile long ClkCount = 0; // number of times clock interrupt has fired

void CLK_ISR() {
  ClkCount++;
}

void setup() {
  Serial.begin(115200);
  long startTime = millis();

  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to wifi");

  attachInterrupt(CLKPin, CLK_ISR, RISING);

  //Set the CLK-pin to input
  pinMode(CLKPin, INPUT);
}

void loop() {
  if (millis() > nextPrint) {
    Serial.print("Freq is: ");
    Serial.println(ClkCount);
    ClkCount = 0;
    nextPrint += 1000;
  }
  yield();
}

It always gets in a reboot/crash loop (no idea why the first few counts are wrong - I guess the ESP isn't ready yet):
Connecting to SSID ...
.Connected to wifi
Freq is: 1
Freq is: 1
Freq is: 0
Freq is: 0
Freq is: 1
Freq is: 0
Freq is: 2313
Freq is: 6667
Freq is: 6666
Freq is: 6667
Freq is: 6667
Freq is: 6667
Freq is: 6667
Freq is: 6667
Freq is: 6667
Freq is: 6667

Exception (0):
epc1=0x40202034 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: sys
sp: 3ffffc40 end: 3fffffb0 offset: 01a0

>>>stack>>>
3ffffde0:  401067da 00000026 00000000 00000001
3ffffdf0:  c0017025 3ffe8d04 3ffee188 00000001
3ffffe00:  00000003 00000008 3ffee99c 00000022
3ffffe10:  3fffc200 401067a0 3fffc258 4000050c
3ffffe20:  40004384 00000030 00000012 ffffffff
3ffffe30:  60000200 00000006 30043003 80000000
3ffffe40:  20000000 3fff0c38 80000000 203fc120
3ffffe50:  00000000 3fffc6fc 00000001 3fff0c3c
3ffffe60:  00000154 003fc120 60000600 00000030
3ffffe70:  40106845 00000080 00000022 3fffc200
3ffffe80:  c0017025 3fffc258 4000050c 00000022
3ffffe90:  3fffc200 401067a0 3fffc258 00000022
3ffffea0:  3fffc200 401067a0 3fffc258 4000050c
3ffffeb0:  40202b20 00000030 00000012 ffffffff
3ffffec0:  40000f49 3ffee9e8 00000000 3fffd9d0
3ffffed0:  00000000 00000000 00000000 fffffffe
3ffffee0:  ffffffff 3fffc6fc 00000001 3fffdab0
3ffffef0:  00000000 3fffdad0 3ffee9e8 00000030
3fffff00:  3ffee99c 0000000a 3ffe8bc8 402094cc
3fffff10:  00000000 400042db 3ffeff84 40104580
3fffff20:  40004b31 3fff0b84 000001f4 003fc080
3fffff30:  40105aac 000001f4 3ffed190 401004f4
3fffff40:  40106e4d 3fff0b84 00000000 00f8676f
3fffff50:  3ffe8bc8 3ffe8d04 3ffed190 40224d02
3fffff60:  40223d49 40223d52 3ffed004 3ffee1b0
3fffff70:  40228445 3ffed004 3ffee1b0 00f857fe
3fffff80:  4022848a 3fffdab0 00000000 3fffdcb0
3fffff90:  3ffee1c8 3fffdad0 3ffee9e8 40202b43
3fffffa0:  40000f49 40000f49 3fffdab0 40000f49
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

What am I doing wrong, or is it just not possible to stay connected to WiFi while using interrupts on an ESP8266?


texts: Problem “Didn't find PN53x board” Arduino NFC Card Reader

texts:
i am using the elechouse PN532 RFID Module with an Wemos D1 mini in the Arduino IDE.
I use the ISO1443a_uid example from the elechouse library. All works fine if i plug the USB Cable into the wemos and the demo runs. But if i press the reset button on the Wemos D1 mini then the Serial brings this output:

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v0fd86a07
~ld
Hello!
Didn't find PN53x board

Sometimes it works fine but mostly comes this error.

Here is the sample code (i am using the I2C Mode):

* When the number after #if set as 1, it will be switch to SPI Mode*/
if 0
 #include <SPI.h>
 #include <PN532_SPI.h>
 #include "PN532.h"

 PN532_SPI pn532spi(SPI, 10);
 PN532 nfc(pn532spi);

* When the number after #elif set as 1, it will be switch to HSU Mode*/
elif 0
 #include <PN532_HSU.h>
 #include <PN532.h>

 PN532_HSU pn532hsu(Serial1);
 PN532 nfc(pn532hsu);

* When the number after #if & #elif set as 0, it will be switch to I2C Mode*/
else
 #include <Wire.h>
 #include <PN532_I2C.h>
 #include <PN532.h>
 #include <NfcAdapter.h>

 PN532_I2C pn532i2c(Wire);
 PN532 nfc(pn532i2c);
endif

oid setup(void) {
 Serial.begin(115200);
 Serial.println("Hello!");
 pinMode(D2,INPUT_PULLUP);
 pinMode(D1,INPUT_PULLUP);
 nfc.begin();

 uint32_t versiondata = nfc.getFirmwareVersion();
 if (! versiondata) {
   Serial.print("Didn't find PN53x board");
   while (1); // halt
 }

 // Got ok data, print it out!
 Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
 Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
 Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

 // Set the max number of retry attempts to read from a card
 // This prevents us from waiting forever for a card, which is
 // the default behaviour of the PN532.
 nfc.setPassiveActivationRetries(0xFF);

 // configure board to read RFID tags
 nfc.SAMConfig();

 Serial.println("Waiting for an ISO14443A card");

oid loop(void) {
 boolean success;
 uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
 uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

 // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
 // 'uid' will be populated with the UID, and uidLength will indicate
 // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
 success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

 if (success) {
   Serial.println("Found a card!");
   Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
   Serial.print("UID Value: ");
   for (uint8_t i=0; i < uidLength; i++)
   {
     Serial.print(" 0x");Serial.print(uid[i], HEX);
   }
   Serial.println("");
   // Wait 1 second before continuing
   delay(1000);
 }
 else
 {
   // PN532 probably timed out waiting for a card
   Serial.println("Timed out waiting for a card");
 }

What is wrong? why is it not alltimes working after a reset?


texts:
I'm making a control system for the heating of a plate using a PID control.

the goal is to regulate the temperature of the plate by changing the power dissipated by the resistance. By using a sensor I read the temperature  of the plate and is then used as the input in the PID control.
I programmed also a signal wave square for the PWM.

but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive.
and I cannot connect between the PWM and the PID.

Code of the square signal:

void setup()
{
  pinMode(9, OUTPUT);
}
void loop()
{
   // phase haute
   digitalWrite(9,HIGH);
   delay(30);
   // phase basse
   digitalWrite(9,LOW);
   delay(70);
   //ton+toff = 0.1;
//   ton = 0.1*Output;
}

Code of PID and the sensor

/********************************************************
 * PID Basic Example
 * Reading analog input 0 to control analog PWM output 3
 ********************************************************/

#include <PID_v1.h>

int val;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);

void setup()
{
  Serial.begin(9600);
  //initialize the variables we're linked to
  Input = analogRead(1);
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  val = analogRead(1);
  float mv = ( val/1024.0)*5000;
  float Input = mv/10;
  myPID.Compute();
  analogWrite(3,Output);
  Serial.print("input temperature is :");
  Serial.println(Input);
  delay (1000);
//  delay(1000);
  Serial.print("output is :");
  Serial.println(Output);
  delay(1000);
}

Thank you in advance


texts: Error building Arduino WiShield Flash example: 'dflash' was not declared in this scope

texts:
I'm using WiShield library from: https://github.com/jcmuller/WiShield

What is wrong with this library?

The code:

/*
 * Web Server using Flash
 *
 * A simple web server example using the WiShield 2.0
 * that reads the manufacturing ID from the Flash and
 * displays it on a webpage.
 */

#include <WiShield.h>
#include <dataflash.h>

#define WIRELESS_MODE_INFRA    1
#define WIRELESS_MODE_ADHOC    2

#define FLASH_SLAVE_SELECT 7
#define WIFI_SLAVE_SELECT  10

// Wireless configuration parameters ----------------------------------------
unsigned char local_ip[] = {192,168,1,2};   // IP address of WiShield
unsigned char gateway_ip[] = {192,168,1,1}; // router or gateway IP address
unsigned char subnet_mask[] = {255,255,255,0};  // subnet mask for the local network
const prog_char ssid[] PROGMEM = {"ASYNCLABS"}; // max 32 bytes

unsigned char security_type = 0;    // 0 - open; 1 - WEP; 2 - WPA; 3 - WPA2

// WPA/WPA2 passphrase
const prog_char security_passphrase[] PROGMEM = {"12345678"};   // max 64 characters

// WEP 128-bit keys
// sample HEX keys
prog_uchar wep_keys[] PROGMEM = {   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,     0x09, 0x0a, 0x0b, 0x0c, 0x0d,   // Key 0
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 1
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 2
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00    // Key 3
                            };

// setup the wireless mode
// infrastructure - connect to AP
// adhoc - connect to another WiFi device
unsigned char wireless_mode = WIRELESS_MODE_INFRA;

unsigned char ssid_len;
unsigned char security_passphrase_len;
//---------------------------------------------------------------------------

unsigned char mfg_id[4];

void setup()
{
  initShield();
}

// This is the webpage that is served up by the webserver
const prog_char webpage[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type:     text/html\r\n\r\n"
                                ""
                                ""
                                "
Flash Mfg ID: 000 000 000
"
                                "<form method=post action=\"/upload\" enctype=\"multipart/form-data\">"
                                "FS Image Upload"
                                "
"
                                "<input type=file name=i size=40> &nbsp; <input type=submit value=\"Upload\">"
                                "</form>"
                                ""
                                "";

void loop()
{
  dflash.read_id(mfg_id);

  WiFi.run();
}

void initShield()
{
  // there is some contention on the SPI between the flash and wifi chip,
  // so disable both devices at the beginning until they are properly
  // initialized by their respective libraries
  pinMode(FLASH_SLAVE_SELECT, OUTPUT);
  digitalWrite(FLASH_SLAVE_SELECT, HIGH);
  pinMode(WIFI_SLAVE_SELECT, OUTPUT);
  digitalWrite(WIFI_SLAVE_SELECT, HIGH);

  // now init dataflash
  dflash.init(FLASH_SLAVE_SELECT);

  // now init wifi
  WiFi.init();
}


texts: ESP-01 not waking correctly up after deep sleep

texts:
I have an ESP-01 that I want to measure pool temperature with. It will send the data over MQTT to the broker.

I have connected RST to GPIO16 so I can use the deep sleep functionality. Currently I am testing sending a "hello world" to the MQTT broker, and everything works fine when booting up the first time, but it seems like the ESP never wakes up correctly after the first deep sleep.

My script looks like this:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// Set ADC mode
ADC_MODE(ADC_VCC);

// WiFi settings
const char* ssid = "Network";
const char* password = "Password";
IPAddress ip(192, 168, 0, 100);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);

// MQTT settings
const char* mqtt_server = "192.168.0.110";
const int mqtt_port = 1883;
const char* mqtt_user = "User";
const char* mqtt_pass = "Password";
const char* mqtt_client_name = "poolsensor";
const char* mqtt_topic = "pool";

// Data wire plugged into D1 on the ESP8266 ESP-01 - GPIO 5
#define ONE_WIRE_BUS 5

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

// Pass our OneWire reference to Dallas Temperature
DallasTemperature DS18B20(&oneWire);

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
  delay(10);

  // Annuonce connection
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Setup WiFi config and connect
  WiFi.mode(WIFI_STA);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're connected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");

    // Attempt to connect
    if (client.connect(mqtt_client_name, mqtt_user, mqtt_pass)) {
      // Success
      Serial.println("connected");
    } else {
      // Fail
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

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

  // Start WiFi setup
  setup_wifi();

  // Set MQTT server
  client.setServer(mqtt_server, mqtt_port);

  // Set resolution to 0.25
  DS18B20.setResolution(10);

  // Start sensor
  DS18B20.begin();
}

void loop() {
  if (!client.connected()) {
    reconnect();
  } else {
    // Get temperature
    /*
    DS18B20.requestTemperatures();
    float temp = DS18B20.getTempCByIndex(0);

    if ((temp > -20) && (temp < 60)) {
      client.publish("pool/temperature", String(temp).c_str(), true);
    }
    */

    client.publish("pool/temperature", "hello world");
    Serial.println("published temperature");

    delay(1000);

    // Sleep
    ESP.deepSleep(60 * 1000000);

    delay(3000);
  }
}

Everything looks good in the serial monitor when compiling and uploading code, as the code runs the first time:

Connecting to Network
......
Connected, IP address: 192.168.0.100
Attempting MQTT connection...connected
published temperature

And I can see in my MQTT debugger that it receives hello world. After around 60 seconds, the following is shown in the serial monitor (lots of gibberish):

{l�l��|��d�|�d�b<����s�c$�#��ng�lgn���cxp��${$sd�s��'�c�ncp��

This is the last message I ever receive from the ESP, so I assume it never deep sleeps again and runs over the code again.

Anyone experienced the same, or see a bug in my code?


texts: How do I combine a variable and characters into a string with Arduino?

texts:
I am building some sensors with Arduinos, which each have a unique integer address from 1-9 (This address is an int variable stored in a struct 'Matrix', the variable name is Matrix.Address). The sensors will all be connected to a PLC via SoftwareSerial (BitBanging) through an RS232 converter. Since all of the Sensors will be connected to the same RX & TX ports on the PLC, I need a way to address each sensor through a unique string.

My plan is the following:

*If the PLC wants a reading from sensor #1, it will send the string: "1,read"
All of the sensors should receive this string, but I only want the sensor with address '1' to respond.

*What I am trying to do is come up with a line of code similar to the following:

    if (plcCommand == (Matrix.Address + ",read<CR>")) {
  mySerial.print(GenerateEquation());

Basically, I need to insert that 'Matrix.Address' variable into a string which will be compared to the incoming string.

It seems like a very simple thing to do, but I am having trouble coming up with a solution.

Any help would be appreciated!


texts: What if Ultrasonic sensor doesn't detect object?

texts: I am trying to write a sketch where a function will only be triggered when the ultrasound doesn't return back. Thus when the echo pin is checked after 1 second after the trigger pin was written high, it must be low. Will it be a digitalRead function?


texts: Is there a Serial write buffer limit and does the Arduino reset if it is hit?

texts:
I have an Arduino Mega 2560 that is resetting every 32 seconds if the serial monitor is not attached. Just before it resets, there is a flash of TX, then it goes. If ther serial monitor is attached it runs forever. Clearly I can't use the serial monitor to debug this so am clutching at straws as to what is happening.

Update:

Having eliminated all code and uploaded an empty sketch, no includes etc., the board still exhibits the reset. However, I have an Adafruit Ultimate GPS attached to the GND, 5V, TX1 and RX1 pins. When I remove it the resets stop. But with it attached and the serial monitor attached to the board, the resets also stop, even with an empty sketch. Spooky.

So, is it possible the GPS unit is filling a receive buffer, even if the serial port isn't set up to receive? I still have a problem that while I'm clearing and logging the GPS data, the resets are still at a regular 32 seconds, thus the reason I'm working on it still.

Note: The flash of TX no longer shows up with the empty sketch.


texts:
My project is to control a dual motor model boat via bluetooth hand-held device. I am using an Adafruit feather 32u4 bluefruit LE and Adafruit DC Motor + Stepper FeatherWing Add-on. I am using the Apple IOS Adafruit Bluefreuit BLE app as the controller. I have this part of the design nearly done.  I plan to use this in a swimming pool.

How can I have the boat automatically avoid the sides of the pool or any other obstruction?  Also how can I have the boat steer toward a buoy in the water?

I would like to have any solutions as low-cost.

Thanks in advance


texts: Arduino Uno and ESP01: can't issue AT commands [Solved]

texts:
I would like to connect an Arduino Uno and an ESP 01 module. I use the Arduino IDE and I tried to test communication via serial monitor. I get the "ready" message from the ESP 01, but I am not able to issue AT commands from the serial monitor. It only displays random characters on the console.

It seems that no newline character is issued, because if I try to insert commands, they are inserted next to previous characters. I use "Both NL & CR" and 115200 baud settings in Arduino IDE. I tried 9600 baud too, but then the text is unreadable.

I used the following pins on my ESP-01:

Vcc -> 3,3V
Gnd -> Gnd
Rx  -> Tx(pin 0) of my Arduino, used voltage divider to make it 3.3V.
Tx  -> Rx(pin 1) of Arduino
CH_PD -> 3.3V

Please see serial monitor screenshot:

EDIT: PROBLEM RESOLVED:

My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.


texts: minimal code for multiple buttons de-bouncing

texts:
i have 4 buttons attached to 4 pins configured as inputs with internal pull-up activated...

is this function sufficient to get a debounced state of the pressed button?

byte buttonPressed(){
  byte btn = 0;
  if (digitalRead(30)==LOW) btn = 1; else
  if (digitalRead(9)==LOW) btn = 2; else
  if (digitalRead(31)==LOW) btn = 3; else
  if (digitalRead(8)==LOW) btn = 4;
  delay(20);
  return btn;
}

any strictly necessary improvements are welcome...


texts: How do I synchronize data from multiple sensors and time from a GPS module?

texts: I'm working on a project that takes data from an EMG muscle sensor and a heart rate sensor and synchronizes it with the time from a GPS module. The data is then sent to a local router. Can someone please provide the code for this??


texts: Sleep mode Arduino Due through IR receiver control

texts:
I need to put my Arduino Due into sleep mode in order to consume less power. My Arduino Due receives IR data and does some work with it, but I need to make it sleep until there is no data. If data appears it should wake up and do something with data and go back to sleep mode.

Is there any way to do this? I would be grateful for any help.


texts:
So basically I'm making 2 buttons turn on and off 2 different LEDs using debounce.
I got that settled with one button to turn on and off 1 LED.
But how do I make it so I can use the same lines but obviously different names of pins in Void loop?

So this is the one command line, but how do I make 2 commands with the if statement, may I have an example? Thanks

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;         // the number of the input pin
int inPin2 = 26;
int outPin1 = 13;       // the number of the output pin
int outPin2 = 6;

int state = LOW;      // the current state of the output pin
int reading;           // the current reading from the input pin
int reading2;
int previous = HIGH;    // the previous reading from the input pin
int previous2 = HIGH;

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

//===============================================================================================
void doIt(int outPin)
{
  Serial.print("Button Switch State Change:");
  if (state == HIGH) state = LOW;
  else state = HIGH;
  Serial.println(state);
  lcd.clear();
  lcd.print("Zone1|State: ");
  lcd.print(state ? F("On") : F("Off"));
  Serial.print(state ? F("On") : F("Off"));
  digitalWrite(outPin, state);
}
//===============================================================================================
void setup()
{
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("System Activated");
  //
  lcd.setCursor(0, 1);
  lcd.print("Ready...");

  pinMode(inPin, INPUT);
  pinMode(outPin1, OUTPUT);
  pinMode(inPin2, INPUT);
  pinMode(outPin2, OUTPUT);

  Serial.begin(9600);
  Serial.println("System Activated");
  Serial.println("Made by Mateo Holguin");
  Serial.println("0 = Light is Off | 1 = Light is On");
  Serial.println("=======================================");
}

//===============================================================================================

void loop()
{
  reading = digitalRead(inPin);
  reading2 = digitalRead(inPin2);

  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    doIt(outPin1);
  }
  else if (reading2 == HIGH && previous2 == LOW && millis() - time > debounce){
    doIt(outPin2);
  }

  previous = reading;
  previous2 = reading2;
  time = millis();
}


texts: how to change increase pwm frequency by changing resolution?

texts:
As told in this post:

http://forum.arduino.cc/index.php/topic,16612.0.html#

The arduino can achive up to 62.5khz with 8 bits resolution

adding this line in the setup:

TCCR0B = TCCR0B & 0b11111000 | 0x01

sets the divisor of the timer to 1

int output = 5;
void setup() {
  // put your setup code here, to run once:
  TCCR0B = TCCR0B & 0b11111000 | 0x01;

}

void loop() {
  analogWrite(output,127);

}

But I need a frequency of 100khz or as close as possible, the 8 bits resolution is not necessary of my porpouse, it will work just fine with 6 or 7 bits.


texts: ST7920 and u8g2 only using some of a 128x64 display

texts:
I am trying to use the u8g2 library and an Arduino Mega to control an LCD display. Adapting HelloWorld from the examples included in the library to use the SPI ports of the Mega (50-52), I have the code below.
This gives a bit of a disappointing greeting as in the picture below. It seems that the Arduino is not accessing all the pixels, and only able to change the states of three blocks (the top one with "Hello V", and the two darker regions at the bottom).

The display is a 128X64ZW-10 salvaged from a 3D printer which was working when connected to the printer's motherboard. Pin-out deduced by some kind folk here and here (translation). I briefly saw random Pinyin characters flash across the whole display while I was switching wires. These two facts, and the fact that the regions of pixels that are working are not arranged at random, makes me suspect it is a wiring or coding issue, and that the pixels are not dead.
Here is the code:
#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

int LCD_CLK_PIN = 52; //Clock (white)
int LCD_RW_PIN = 50; //Read-Write (blue)
int LCD_RS_PIN = 51;  //Register Select (green)
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, LCD_CLK_PIN, LCD_RW_PIN, LCD_RS_PIN,U8X8_PIN_NONE);

void setup(void) {

  /* U8g2 Project: SSD1306 Test Board */
  //pinMode(10, OUTPUT);
  //pinMode(9, OUTPUT);
  //digitalWrite(10, 0);
  //digitalWrite(9, 0);

  /* U8g2 Project: T6963 Test Board */
  //pinMode(18, OUTPUT);
  //digitalWrite(18, 1);

  /* U8g2 Project: KS0108 Test Board */
  //pinMode(16, OUTPUT);
  //digitalWrite(16, 0);

  /* U8g2 Project: LC7981 Test Board, connect RW to GND */
  //pinMode(17, OUTPUT);
  //digitalWrite(17, 0);

  /* U8g2 Project: Pax Instruments Shield: Enable Backlight */
  //pinMode(6, OUTPUT);
  //digitalWrite(6, 0);

  u8g2.begin();
}

void loop(void) {
  u8g2.firstPage();
  do {
    u8g2.setFont(u8g2_font_ncenB10_tr);
    u8g2.drawStr(1,18,"Hello World!");
  } while ( u8g2.nextPage() );
  //delay(1000);
}

I have spent a couple of days on this, but no luck. Any ideas?


texts: Arduino Nano 3.0 dimensions without the pins

texts: I think the title of this question is quite clear. I am looking for the exact dimensions of the Arduino Nano 3.0, with the electronic components and the USB mini port on the IC (the Atmega328 one), without the external pins.


texts: Seems like I cant control 4 stepper motor at once

texts:
Im trying to control 4 stepper motors with the AccelStepper library.
Something like this:
AccelStepper FL(1,stepPin,dirPin);
AccelStepper FR(1,stepPin2,dirPin2);
AccelStepper BL(1,stepPin3,dirPin3);
//AccelStepper BR(1,stepPin4,dirPin4);

The problem is, It works just fine if I declare 3 instance of the AccelStepper, but once I uncomment the 4th one there's an error.
Error message: Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "ESP32 Dev Module, Disabled, Default, 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, None"

In file included from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/esp32/xtensa/xtruntime.h:30:0,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/portmacro.h:80,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/portable.h:94,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/FreeRTOS.h:105,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/Arduino.h:32,

                 from sketch\Test_file.ino.cpp:1:

C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/esp32/xtensa/config/specreg.h:40:13: error: expected unqualified-id before numeric constant

 #define BR  4

             ^

C:\Users\Parit\Desktop\Test_file\Test_file.ino:31:14: note: in expansion of macro 'BR'

 AccelStepper BR(1,stepPin4,dirPin4);

              ^

Multiple libraries were found for "WiFi.h"

 Used: C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\libraries\WiFi

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\WiFi

exit status 1

Error compiling for board ESP32 Dev Module.

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

Im not sure if the problem is the ESP 32 or the code. I use the A4988 driver to connect with all 4 stepper motors.


texts:
I’m trying to sample an AC signal on the Arduino Due. The AC signal will never exceed +-80mv across a frequency range of 6-833Hz. Current is negligible.

I believe there are clamping diodes to protect from this but cannot find any datasheets for the Due.

I understand that the Due cannot read negative voltage but can a negative voltage damage the ADC or it’s accuracy?


texts: So in a laptop you have a CPU and a hard drive. The hard drive feeds data to the CPU and the CPU executes it. In Arduino you flash the CPU and the "hard drive" is built into it. Is it possible to have a hard drive or SD card feed data into the Arduino to be executed and then feed more data in and so on? If it is possible how is it done?


texts: SKETCH quits working after unplugging from computer

texts: Arduino Sketch program runs fine as long as it stays plugged in usb to computer. If I plug in a different power source the sketch quits working. I have plug back in usb and re-download ??? It stops working if I unplug from computer than plug right back in. I have to re down load every time.


texts: Arduino ultrasonic sensor to trigger LED when path is blocked

texts:
I'm working on a project which has falling objects non stop, I only want to detect when objects block the sensors set trigger area. Any suggestions would be great!

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin1 9 // LED 1

int maximumRange = 300; // Maximum range needed
int minimumRange = 10; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
    Serial.begin(9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(LEDPin1, OUTPUT);
}

void loop() {
    /* The following trigPin/echoPin cycle is used to determine the
    distance of the nearest object by bouncing soundwaves off of it. */
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

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

    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    //Calculate the distance (in cm) based on the speed of sound.
    distance = duration/58.2;

    //If the distance is beyond the limits - then nothing happens ie,
    //more than 3 meters or less than 10 cm
    if (distance >= maximumRange || distance <= minimumRange) {
        Serial.println("Nothing Happens");
        digitalWrite(LEDPin1, LOW);
    } else {
        Serial.println("Trigger");
        digitalWrite(LEDPin1, HIGH);
        delay(200);
        delay(50);
    }
}

Arduino uno
4 pin ultrasonic sensor


texts:
I currently have a push solenoid connected to my standard Arduino board. The Arduino is powered via its USB cable, while the solenoid is powered using a 12V Huawei adapter (in conjunction with a MOSFET driver module).

How can I switch out the push solenoid for a servo motor? The operational voltage of the servo is 4.8 to 7.2V (with a stall torque of 13 kg-cm) to give you an idea of its size. I have been told to buy a DC-DC step-down module (to adjust the Huawei supply from 12V down to 5V) but I think it could be easier to power the servo using some sort of USB?

Or other suggestions are welcome. I want the easiest solution (since I am NOT tech savvy) and I can't buy parts until I am for certain the solution will work (that's research for you). Thanks!


texts: Where can I know voltage between GND(ground) and each port of UNO R3?

texts:
Currently I'm new to arduino uno r3.
Where can I find each voltage between each port and GND(ground)?
Or can the voltage be changed?
I don't want to break my led bulbs since large difference of 2 potentials


texts: Arduino stops working when servo makes a few rotations

texts:
The sketch rotates servo back and forth with buttons.
When I rotate servo MG 995/996R 2-4 times Arduino stops working. Its voltage step-down transformer switches from ~9V to ~3.7V which is not enough for Arduino. To make it work again, I must turn off-on the device.

There is no such a glitch with smaller servos such as SG90.


texts: Global variables with C++ in multiple files

texts:
I'm not a C++ programmer (but I have used regular C code for implementing low-level machine language equivalent SW for some time), and after trying to modify an existing cC+ program to do what I need (and failing), I've decided to rewrite parts of the code in plain C code.

But to be able to use the data, I need to create some variables that have to be accessible to parts of the existing C++ code.

When I declare a global variable (extern int variable name;) outside the main program, the compile fails because the references to the global variable aren't within the scope of the cpp parts of the program.

I don't program with multiple files myself, so I was wondering if I need to globally declare the same variables as part of each cpp program that needs to have access to the variables? Is there a another/better way?


texts: Do I use 3,3V or 5V, when device supports both?

texts:
I have a general question regarding the power-supply of the electronic components, that are attached to an Arduino.

If I have a device that operates at voltages between 3,3V and 5V (e.g. this RS232 to ttl converter), what is the best way to connect it with the Arduino?

  Connect 3.3V or 5V power supply between VCC and GND

I know, that you can not draw as much current out of the 3,3V Pin like on the 5V Pin. But what if I don't need much current anyways (like in the linked example)?

What ware the advantages / disadvantages of connecting it to 3.3V and 5V?


texts: Arduino code to control 4 led's from 4 buttons

texts:
This is my very first arduino sketch and it's causing me a bit of a headache.
Sounds so simple really all I want the sketch to do is digitalread from one of 4 digital input pins and then digitalwrite to one of 4 output pins in essence.
So that when button 1 is pressed LED 1 lights up, button 2 pressed led 2 lights up and so on.
I've added a serial write so I could check that the buttons are actually working when pressed.

The code I've written:

const int buttonPin1 = 7;     // number of pushbutton 1 pin
int buttonState1 = LOW;       // set the default variable value for pushbutton1 status
const int ledPin1 =  6;       // number of the LED 1 pin
const int buttonPin2 = 8;     // number of pushbutton 2 pin
int buttonState2 = LOW;       // set the default variable value for pushbutton2 status
const int ledPin2 =  9;       // number of the LED 2 pin
const int buttonPin3 = 4;     // number of pushbutton 3 pin
int buttonState3 = LOW;       // set the default variable value for pushbutton3 status
const int ledPin3 =  5;       // number of the LED 3 pin
const int buttonPin4 = 2;     // number of pushbutton 4 pin
int buttonState4 = LOW;       // set the default variable value for pushbutton4 status
const int ledPin4 =  3;       // number of the LED 4 pin

void setup() {                  // Set Pins to Outputs Or Inputs
  pinMode(buttonPin1, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin1, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin2, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin2, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin3, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin3, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin4, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin4, OUTPUT);     // initialize the LED pins as an outputs:
  Serial.begin(9600);           // initialize serial communication at 9600 baud
}

void loop() {

buttonState1 = digitalRead(buttonPin1);  // read current states of the pushbutton value:
  buttonState2 = digitalRead(buttonPin2);  // read current states of the pushbutton value:
  buttonState3 = digitalRead(buttonPin3);  // read current states of the pushbutton value:
  buttonState4 = digitalRead(buttonPin4);  // read current states of the pushbutton value:

// check if the pushbutton is pressed buttonState# == HIGH/LOW
  // if pressed change buttonState == HIGH to turn on ledPin#
  // else if buttonState == LOW then digitalWrite(ledPin#, LOW) Keeps Led off.

if (buttonState1 == HIGH) {    //check buttonState
digitalWrite(ledPin1, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin1, LOW);   // turn LED off:
}
Serial.println(buttonState1); //Print buttonState to serial
if (buttonState2 == HIGH) {   //check buttonState
digitalWrite(ledPin2, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin2, LOW);   // turn LED off:
delay(10);
}
Serial.println(buttonState2); //Print buttonState to serial
if (buttonState3 == HIGH) {   //check buttonState
digitalWrite(ledPin3, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin3, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState3); //Print buttonState to serial
}
if (buttonState4 == HIGH) {   //check buttonState
digitalWrite(ledPin4, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin4, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState4); //Print buttonState to serial
}

The Leds all have a common GND and the buttons all have a common GND.
Buttons are connected to +5V & Input pin# so one terminal has got two wires,
Led's are connected to digital output pins then resistor and straight to GND.
What happens is that ALL of the LED's come on when any one of the 4 buttons in pressed.

I've attempted to edit some of the code in the example sketches to get this to work.

Can anyone suggest anything that I'm doing wrong?
Or ammend the code sp that I can see where I'm going wrong.


texts: How Do I Control the Onboard LEDs of My Arduino Nano 33 BLE Sense?

texts:
I picked up my Arduino Nano 33 BLE Sense for the first time in a while and ran the classic "Blink" sketch to make sure it was alright. After slight usage, I wanted to play with the onboard LEDs. When I run the following code, the onboard LED does not turn on:
#define RED 22

void setup() {
    pinMode(RED, OUTPUT);
}

void loop() {
    digitalWrite(RED, HIGH);
}

However when I run the following code, the onboard LED does turn on and stays on - it doesn't blink:
#define RED 22

void setup() {
    pinMode(RED, OUTPUT);
}

void loop() {
    digitalWrite(RED, LOW);
    delay(1000);
    digitalWrite(RED, HIGH);
}

What's happening? Is my Nano busted?


texts: Interfacing unusual 4 digits 7 segments display

texts:
There is a common anode and common cathode of 7 segments display. But I got an unusual one.
There are 7 pins controlling 4 digits 7 segments.

I find the pinout by a multimeter. Basically, each pin can be anode or cathode.

My questions:

What is the exact name of this 7 segments display?
How to drive this display by Arduino, any website/sample code?
If I am using the 5V tolerant board, which resistor I need to use? And how is the schematic?


texts: How can I write an integer to a Mifare RFID card using the RFID library?

texts:
I'm a beginner to C++ and I'm clearly missing some fundamental knowledge of data types. As such, I'm struggling to adapt the examples in the miguelbalboa/rfid library to my use case. I'm simply trying to write an integer to a 13.56Mhz RFID tag. Ideally I'd like to optimize the data so as to be quick to read (it seems fully reading these cards can take a while and I'd like to read the integer, an ID, as quickly as possible).

So on to my actual questions... what is the data type shown in this block of example code (shown below) and how can I turn an integer into the same data type? Finally, how should I read this saved value back into the familiar integer data type?

byte dataBlock[]    = {
    0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
    0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
    0x09, 0x0a, 0xff, 0x0b, //  9, 10, 255, 11,
    0x0c, 0x0d, 0x0e, 0x0f  // 12, 13, 14, 15
};


texts: How do I get the request params from a ESPAsyncWebServer?

texts:
I currently have the following code

server.on("/on", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("ON hit.");
    String message;
    Serial.println(request->url());
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = " not specified";
    }
    request->send(200, "text/plain", "On, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);
....

When sending in a request I get the out put, "Device not specified".

I take a look at the request-params() which gives me back a count of params that are in there and it's returning 1. I write this out:

server.on("/off", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("OFF hit.");
    String message;
    int params = request->params();
    Serial.printf("%d params sent in\n", params);
    for (int i = 0; i < params; i++)
    {
        AsyncWebParameter *p = request->getParam(i);
        if (p->isFile())
        {
            Serial.printf("_FILE[%s]: %s, size: %u", p->name().c_str(), p->value().c_str(), p->size());
        }
        else if (p->isPost())
        {
            Serial.printf("_POST[%s]: %s", p->name().c_str(), p->value().c_str());
        }
        else
        {
            Serial.printf("_GET[%s]: %s", p->name().c_str(), p->value().c_str());
        }
    }
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = "not specified";
    }
    request->send(200, "text/plain", "Off, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);

and get the output now of

1 params sent in
_POST[device]: puddle
Device not specified

If I try to do something like request->getParam(0)->value().c_str()
I get a stack dump of a bunch of hex values that I have no idea what it means: but it looks like a big fat error.


texts:
I am making a led cube where sequential lighting is used. So basically i need to repeat my commands for a given time. After much reasearch nothing turned up so decided to ask here.

Here is the code i need to reproduce in a working format

void loop(){
  runfor(500){
    DigitalWrite(5,HIGH);   //this is the command to be executed in other
                            //function
  }
}
void runfor(uint32_t duration){
  int timer = millis();
  while((millis()-timer)<=duration){
  //DigitalWrite(5,HIGH); will execute here
  }
}

So basically DigitalWrite(or any other code if used) will be repeatedly executed for 500 milliseconds


texts: Use I2C to control one of three DS3502 Adafruit digital potentiometers on the same I2C bus

texts:
My teammate and I recently purchased a handful of DS3502 digital potentiometers (https://learn.adafruit.com/ds3502-i2c-potentiometer/pinouts) from Adafruit, and we'd like to be able to control them one at a time from an Arduino while they're all on the same I2C bus. While Adafruit does provide example code for how to control this device when not using the A0 & A1 inputs, they unfortunately do not provide code for how to individually address a single potentiometer located on the same I2C bus as other digital pots.
My teammate and I were wondering how we'd go about using an Arduino to control each pot one at a time if they're all on the same bus. We know that A0 & A1 need to be tied to Vcc in different configurations in order to change the address (e.g. tying A0 to Vcc will make the address 0x29), we just don't know what the actual lines of code should be to write a value to that potentiometer.
We also know we need to use the wire library, we just don't have enough experience using I2C to know what the actual commands should be. Thanks for all the help!


texts:
I am using an Arduino and a Pi to control two stepper motors connected to DRV8825 drivers. The Pi communicates with the Arduino through serial, telling the Arduino which motor to move and how far. In the code, my motors are called A and B(the driver connected to pins 2 and 3 is A and the driver connected to pins 4 and 5 is B).
I believe my issue is both a code and hardware problem. Whichever motor is designated as B moves very little, and the driver gets really hot. When the driver on the far left is motor A, there are no issues with it, but when the driver in the middle is motor A, it only works well for a short time before it starts to stall, and it's always hot. Because of this, I believe there is an issue with my code that makes whichever motor designated as B stall, but the driver in the middle has low performance regardless.
I want to eventually create a circuit with up to 10 drivers, so I was hoping that I could get some insight into what I'm doing wrong so that every motor gets close to equal performance. Thank you!
Here is my code:
#include <AccelStepper.h>

#define dirPin 2
#define stepPin 3
#define dirPin2 4
#define stepPin2 5
#define motorInterfaceType 1

int SPEED=200;

AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);
AccelStepper stepper2 = AccelStepper(motorInterfaceType, stepPin2, dirPin2);

//Steps the motor
// Stepper object, number of steps, previous position of stepper motor
void stepMotor(AccelStepper myMotor, String motorSteps, long int previousPosition){
 while (myMotor.currentPosition() != previousPosition+motorSteps.toInt()){
        if (motorSteps.toInt()<0){
          myMotor.setSpeed(-SPEED);
          } else {
          myMotor.setSpeed(SPEED);
          }

        myMotor.runSpeed();
      }
}

void setup()
{
  //Open serial communication
  Serial.begin(9600);
  // Setting the positions and max speeds of the two steppers
  stepper.setCurrentPosition(0);
  stepper.setMaxSpeed(1000);
  stepper2.setCurrentPosition(0);
  stepper.setMaxSpeed(1000);
}

void loop() {
  long int prevPos=stepper.currentPosition();
  long int prevPos2=stepper2.currentPosition();
  String motor="";

  //Stalls the program until new serial data comes in
  while (Serial.available()<=0){}

  if (Serial.available() > 0) {
    motor = Serial.readStringUntil('\n');
    Serial.println(motor);
    if (motor=="A" || motor=="B") {
      Serial.println("Motor received.");
      }
  }
  //Motor end

  //Stalls the program until new serial data comes in
  while (Serial.available()<=0){}

  if (Serial.available() > 0) {
    String steps = Serial.readStringUntil('\n');
    Serial.println(steps);
    if(motor=="A"){
      stepMotor(stepper, steps, prevPos);
      } else if (motor=="B"){
      stepMotor(stepper2, steps, prevPos2);
      }
  }
  //Steps end

  Serial.println("Finished!");
}


texts:
I am trying to read the analog signal from a Pfeiffer TPG 261 Single Gauge (https://www.idealvac.com/files/brochures/Pfeiffer_Single_Gauge_TPG261.pdf)

The pin assignment of the connector I am using is the following:

Here is the circuit I have built:

And here is the code used:

int pressureSensorPin = A0;

int analogValueP = 0;

void setup(void)
{
  Serial.begin(9600);
}
void loop()
{
  analogValueP = analogRead(pressureSensorPin);
  Serial.println(analogValueP);
  delay(1000);
}

Unfortunately the ouput I get with such a build is only 0 with now and then a 1023.

Any idea of what I am doing wrong ?


texts:
Can anybody tell me why these analogWrite() statements are being ignored. The code is entering the "if"statements because the Serial.println() statements are being executed.

    class Pwm
{
  unsigned long previousMillis = 0;
  unsigned long currentMillis;
  int LED;
  int DELAY;
  int up;
  int down;
  int x;

  public:
  Pwm(int led, int Delay) {

    int LED = led;
    pinMode(LED, OUTPUT);

    DELAY = Delay;
    up = 1;
    down = 0;
    x = 0;

  }

  void Update() {
    currentMillis = millis();
    if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 0) {
      up = 1;
      down = 0;
    }
   }
  }

};

// create Flasher Objects
Flasher red(12, 1000, 250);
//Flasher yellow(11, 500, 500);
//Flasher green(10, 250, 1000);
//Flasher blue(8, 250, 500);

// create PWM Objects
Pwm pin9(9,8);

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

void loop()
{
  red.Update();
  //yellow.Update();
  //green.Update();
  //blue.Update();
  pin9.Update();
}

if I load this code everything works fine. I only have issues with the OOP method.

int LED = 9;
int DELAY = 8;
int up = 1;
int down = 0;
int x;
unsigned long currentMillis;
unsigned long previousMillis = 0;

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

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    if (x == 0) {
      up = 1;
      down = 0;
    }
  }
}


texts: I have an Arduino Uno. It doesn't have a lot of memory space, which is a bit of a nuisance. I was wondering:  Is it possible to load a text file from an SD card and compile it on the Arduino into code that the Arduino can use. I don't really care if it is slow or uses 99% of the memory space just to load on the code. If it is possible would this work: use bootup code to load a piece of code to Arduino, dispose of bootup code so there is more code, do what ever that code does, dispose of that code, load new code.


texts: (ultrasonic sensor code : No such file or directory)

texts:
I'm beginning in Arduino I do not understand what the error means. Please tell me where I can find the resources to understand it and allow the code to compile.

#include <RCSwitch.h>
#include <Ultrasonic.h>

Ultrasonic ultrasonic(11,10);
RCSwitch mySwitch = RCSwitch();

int i;

void setup() {
    mySwitch.enableTransmit(4);
}

void loop() {
    i = ultrasonic.Ranging(CM);
    mySwitch.send(i, 24);
    delay(100);
}

  Arduino: 1.8.7 (Windows 7), Board: "Arduino/Genuino Uno"

  433mhz-lcd-water-level-transmitter:2:24: error: Ultrasonic.h: No such
  file or directory

  compilation terminated.

  exit status 1 Ultrasonic.h: No such file or directory

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


texts: Problem uploading to ATMega using ArduinoIDE ("unbricking" "bricked" microcontroller?)

texts:
I've a SparkFun Pro Micro which is an Arduino Leonardo clone. Unfortunately my attempts to upload programs failed. I did some research in the internet and found you have to use SparkFun's configuration. There is a board manager's URL you have to use: https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json

So far so good. After trying to use this I attempted to do an upload and failed. I tried it with different settings but all failed. While earlier there was a serial port named /dev/ttyACM0 there now is no such port any more. Further research gave me the information that you might get the device running if you a) reset to boot loader mode where you should have an 8 seconds window to upload and b) actually perform the upload.

I can verify: If I pull RESET to ground I can switch into this 8 seconds mode. Then the device /dev/ttyACM0 appears after about 1 second for about 7 seconds. As instructed I immediately try to do an upload. This is strange: I immediately (!) get the following output:

Line 1: Sketch uses 4140 bytes (14%) of program storage space. Maximum is 28672 bytes.
Line 2: Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.
Line 3: avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
Line 4: Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

The TTY should be there as the 7 seconds have not been passed in that case. Furthermore my user account is in dialout which enables it to use the tty.

If I trust this error message that means the tty is gone as soon as avrdude tries to access it. Which shouldn't be that way, should it?

Has anyone encountered this situation before? How can I upload a program to the mikrocontroller? Has anyone has any experience with that situation here?

--

Additional information:

ArdunoIDE 1.8.5
Ubuntu (Mate) Linux 16.04


texts:
I have a grbl board that runs on an Atmega328p. On the board I have also provided the ability to control the stepper drivers through an external control step and dir signals. The schematics are shown here. For the sake of simplicity, the Atmega328p's ISP part of the schematic is shown. Now since the datasheet for the MCU says that when its not powered, the MCU pins should not see voltages more than Vcc+0.5V and less than -0.5V. Which is why the control signals from the Atmega328p are OR'd with the external signal inputs. The limit and spindle signals are buffered through a dual buffer.

Now on another revision of the board without this added feature of being driven from an external control logic, everything works great. However, on this board, I'm not able to program the Arduino bootloader using the ISP header (using a Pocket AVR programmer). I'm was not sure if these OR chips and the buffer were interfering somehow which is why I removed them from the board and I'm still not able to program the Atmega328p with the Arduino bootloader. To eliminate a kaput programmer as the cause for the issue, I tried using the programmer on the earlier version board and everything works great there.

TL;DR, ISP programming won't work on this board and I'm not sure if the added OR and buffer chips are interfering. Any help would be appreciated.

The schematics:


texts: How can I set a calculated value when my sketch is uploaded?

texts:
I have an Arduino based countdown timer that counts down the number of minutes remaining to an event and displays them on an LCD. Since the event's start time is fixed, I have to re-calculate my countdown duration and update a constant in the sketch every time I upload it.

Is it possible to calculate the duration on the PC and set the starting value for the timer automatically? Perhaps using some kind of pre-compile script? Or perhaps through some kind of debugging features?

I'm not interested in adding RTC or other hardware to this project b/c (1) I don't have it handy and (2) there's very limited physical space in the already assembled project.

I'm currently using the Arduino IDE but I would be open to solutions that use other IDEs, or external components.


texts:
I am using bluetooth hc-05, arduino uno and ap app created by mit app inventor.The problem is myserial.available is returning 0 and hence its loop is not getting executed. I had connected four pins of the hc-05 module. Rx to pin 10, Tx to pin 11, VCC to 5V, GND to GND. On the app it is showing that the mobile is connected to HC-05 however the condition is not met.

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

String name="";
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  Serial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.println("Bluetooth is connected");
    name=mySerial.read();
    Serial.println(name);
  }
  else
 {
   Serial.println("Bluetooth is not connected");
  }
}


texts: How to upload already compiled code when no changes were made?

texts:
How do I use the Arduino IDE to upload the last compiled code? I don't want to have to wait 2 minutes to upload compiled code when there are no changes. It's a big codebase where I frequently make one or two small changes and have some issue with my MCU or USB cables. Frequently the controller on my boards are damaged due to some overcurrent issue because of the high-heat nature of 3d printing. So having to wait an extra 2-5 minutes every time I experiment with this unacceptable.

Obviously, there is a keyboard shortcut to do this that I'm unaware of. Because otherwise this would add hours to development.

Please tell me how I can get Arduino-IDE to just 'upload without compiling' my sketch.


texts: IDE compiles incorrect file after renaming them

texts:
I am using the stand alone Arduino IDE to build some projects, and I have a few .cpp files now, but during work I renamed them .c and back. When compiling the project now (with Ctrl-R), it is still trying to compile the .c files. But, I don't even see them on disk!
Changing the .cpp makes no difference. I am used to IDEs having some kind of project file, or a "clean project" option, but I cannot find those here.