texts:
The target of this is for the system to print "Done" when distance, measured by 2 ultrasonic sensor, is between 6-17 cm. This is my python code:
import serial
arduinoSerialData = serial.Serial('com4',9600)
while True:
        if arduinoSerialData.inWaiting() > 1:
            myData = arduinoSerialData.readline()
            myData = str(myData)
            myData = myData.replace("b'", '')
            myData = myData.replace("\\r\\n'", '')
            if myData<'17' and myData>'6':
                print("Done!")

and This is my c++ code:
int trigPin=13; //Sensor Trig pin connected to Arduino pin 13
int echoPin=11;  //Sensor Echo pin connected to Arduino pin 11
float pingTime;  //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.
int trigPin1=2; //Sensor Trig pin connected to Arduino pin 13
int echoPin1=3;  //Sensor Echo pin connected to Arduino pin 11
float pingTime1;  //time for ping to travel from sensor to target and return
float targetDistance1; //Distance to Target in inches
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
}

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

  digitalWrite(trigPin1, LOW); //Set trigger pin low
  delayMicroseconds(2000); //Let signal settle
  digitalWrite(trigPin1, HIGH); //Set trigPin high
  delayMicroseconds(15); //Delay in high state
  digitalWrite(trigPin1, LOW); //ping has now been sent
  delayMicroseconds(10); //Delay in low state

  pingTime1 = pulseIn(echoPin1, HIGH);  //pingTime is presented in microceconds
  pingTime1=pingTime1/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime1=pingTime1/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance1= speedOfSound * pingTime1;  //This will be in miles, since speed of sound was miles per hour
  targetDistance1=(targetDistance1)/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance1= targetDistance1*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)
  ;Serial.println(targetDistance1);
  delay(5)

  ;digitalWrite(trigPin, LOW); //Set trigger pin low
  delayMicroseconds(5000); //Let signal settle
  digitalWrite(trigPin, HIGH); //Set trigPin high
  delayMicroseconds(15); //Delay in high state
  digitalWrite(trigPin, LOW); //ping has now been sent
  delayMicroseconds(10); //Delay in low state

  pingTime = pulseIn(echoPin, HIGH);  //pingTime is presented in microceconds
  pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance= speedOfSound * pingTime;  //This will be in miles, since speed of sound was miles per hour
  targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance= targetDistance*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)
  ;Serial.println(targetDistance);

  delay(10); //delay tenth of a  second to slow things down a little.
}

The problem with this is that at first the distance is very large(1000+cm) even though object is 5 cm away from the object.
Secondly, when I remove the if statement in they python code, and object is placed 12 cm from sensor, I can see that the sensor prints it and returns an accurate distance, but when I apply the if statement and carry out using the same circumstances as before, it does not print anything.
I anyone knows why this is happening, Please help!
Thanks!


texts: Opening webpage using ESP8266 in Arduino

texts:
I am trying to open the webpage in ESP8266 via Arduino Mega.
I have successfully opened the webpage if I use the AT command in the Serial Monitor

The output is perfect

+IPD,382:HTTP/1.1 200 OK
Server: nginx
Date: Sun, 08 May 2016 06:44:47 GMT
Content-Type: text/html
Connection: close
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.26
Set-Cookie: PHPSESSID=rnsmo0b4kq07c5mi3mdsu280g4; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

S|R190|W5|O31.0|T0|A24|CLOSED

As you can see the output is fine.
Now If I issue commands using Arduino Serial1.print() and read the output using following code:

 while( Serial1.available() )
 {
     inChar = Serial1.read();
     Serial.write(inChar);
     //delay(1);         //could play around with this value if buffer overflows are occuring
 } // while

The output skips character randomly

+IPD,386:HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 May wed-y: HP/.5.26
SetCooie:PHPESSD=7kameos5kd7aqcn4e54; pth=
Epirs: hu, 19Nov198 0852:0 GT
ach-Cotro: n-stre,no-ach, mst-evaidate,pos-chck=, pe-ceck0
raga: o-cche
F~SR19|W5O310|T90|ENDLOSD

I have tried different values of delay() but of no help.
My baudrate is 9600 for both arduino Serial and ESP8266 Serial1

Can you please tell me what can be the reason.
Thanks


texts:
I am acquiring a Logitech G29 for my PS4 and I want to have an external handbreak. The handbrake only needs an input when active, so no "pressure level" or something like that required, only "on" or "off".
I have come around a few answers such as this, but I am not sure how to make it work on PS4 (and even if it needs some changes what so ever).
I don't have enough knowlegde to ask the correct questions, so I am asking for directions on basically how to send an arduino signal so the PS4 interprets as a joystick command (which in game I will configure as the handbrake option).
I am somewhat aware about the necessity of a custom library, but nothing more than that, not even what that really means to be honest.
The drawing bellow is somewhat the scheme for my project. And it is based on what I understood from this post.

Thank you for your time!


texts: Switch case does not work after booting system

texts:
int value1;
int value2;
int runs1 = 0;
int runs2 = 0;

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2);
int inPin = 6;
int val = 0;
int push_count = 0;
int buttonState = 0;
unsigned long previousMillis = 0;
const long interval = 1800000;
int currentTime;

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

void loop() {

  unsigned long currentMillis = millis();
  currentTime = 30-(currentMillis - previousMillis)/60000;
  if (currentMillis - previousMillis >= interval || previousMillis == 0) {
    previousMillis = currentMillis;

  measure();
  }

  buttons();
}

void measure() {
 value1=300;
 value2=300;

  if (value1 <= 650)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("1");
   delay(2000);

}
else
{
  lcd.clear();
  lcd.print("Pump 1 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs1++; // increment the number of times pump 1 has run

}

  if (value2 <= 550)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");
}
else
{
  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");
}
  }

void buttons() {
  val = digitalRead(inPin);

  if (val != buttonState && val == HIGH){
    push_count++;
  }
      else {
      // do nothing
    }

  buttonState = val;
  switch (push_count) {
    case 0:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 1 reads");
      lcd.setCursor(0,1);
      lcd.print(value1);
      delay(20);
      Serial. print("Case 0");
      push_count++;
      break;
    case 1:
      Serial. print("Case 1");
      break;
    case 2:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 2 reads");
      lcd.setCursor(0,1);
      lcd.print(value2);
      delay(10);
      push_count++;
      break;
    case 3:
      break;
    case 4:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Pump 1 ran");
      lcd.setCursor(0,1);
      lcd.print(runs1);
      lcd.setCursor(5,1);
      lcd.print(" times");
      delay(10);
      push_count++;
      break;
    case 5:
      break;
    case 6:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Pump 2 ran");
      lcd.setCursor(0,1);
      lcd.print(runs2);
      lcd.setCursor(5,1);;
      lcd.print(" times");
      delay(10);
      push_count++;
      break;
    case 7:
      break;
    case 8:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Next cycle in");
      lcd.setCursor(0,1);
      lcd.print(currentTime);
      lcd.setCursor(5,1);
      lcd.print(" Minutes");
      delay(10);
      push_count++;
      break;
    case 9:
      break;
    default:
      push_count=0;
  }
}

When I boot the system (standalone atmega328p circuit) the connected LCD either shows

  Plant

  2

originating from

   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");

or in my real code (where value1 and value2 are actually measured)

  Pump 2 turned ON

  Water for 40 sec

originating from

  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");

after I use the button to cycle through all the cases everything works fine. On the next button press I get to case 2 (-> 3).
After a full cycle case 0 (-> 1) gets displayed correctly.

The above MCVE runs perfectly on my breadboard setup, but not in the real setup.

Here's the schematic of the real setup.

So somewhere in the real setup has to be something that my code does not handle properly. The breadboard setup is minimal, just all GND and VCC connections, a 16 Mhz crystal with 22 pF caps.


texts: OLED display on I2C causes esp8266 to reset

texts:
I have connected two temp sensors and an OLED display to a NodeMCU using I2C. When the program reaches the instruction to print the measurements on the display the program crashes and NodeMCU resets itself. In the serial monitor I see "rst cause 2". I did search about this online but couldn't find a similar issue involving an OLED. I wonder what is causing this reset and how to fix it?
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Sodaq_SHT2x.h>
#include <Adafruit_SSD1306.h>

//defining OLED dimensions
#define WIDTH 128
#define HEIGHT 32
#define OLED_RESET -1

Adafruit_SSD1306 display(OLED_RESET);

Adafruit_BME280 bme1; // I2C

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

  Wire.begin();
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initiate OLED

  Serial.println(F("BME280 test"));

  //BME280 sensor 1
  if (! bme1.begin(0x77, &Wire)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

  //  weather monitoring
//  Serial.println("-- Weather Station Scenario --");
//  Serial.println("forced mode, 1x temperature / 1x humidity / 1x pressure oversampling,");
//  Serial.println("filter off");
  bme1.setSampling(Adafruit_BME280::MODE_FORCED,
                   Adafruit_BME280::SAMPLING_X1, // temperature
                   Adafruit_BME280::SAMPLING_X1, // pressure
                   Adafruit_BME280::SAMPLING_X1, // humidity
                   Adafruit_BME280::FILTER_OFF   );
}

void loop() {
  unsigned long newTime = millis();
  static unsigned long oldTime = 0;

  if (newTime - oldTime >= 10000) {
    oldTime = newTime;

    float temp1 = 0.0;
    float humid1 = 0.0;
    float temp2 = 0.0;
    float humid2 = 0.0;

    takeReadingsBME(temp1, humid1);
    printValuesBME(temp1, humid1);

    takeReadingsSHT(temp2, humid2);
    printValuesSHT(temp2, humid2);
    displayResults(temp1, temp2, humid1, humid2);
  }
}

void printValuesBME(float temp, float humid) {

  Serial.println();
  Serial.print("BME: ");
  Serial.write(9);
  Serial.print("T = ");
  Serial.print(temp);
  Serial.write(9);
  Serial.print("H = ");
  Serial.println(humid);
}

void printValuesSHT(float temp2, float humid2) {
  Serial.print("SHT21: ");
  Serial.write(9);
  Serial.print("T = ");
  Serial.print(temp2);
  Serial.write(9);
  Serial.print("H = ");
  Serial.println(humid2);
}

void displayResults(float temp1, float temp2, float humid1, float humid2) {
  display.clearDisplay();
  display.setTextColor(WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.print("Sensor Data");
  display.println();
  display.print("BME ");
  display.print("T = ");
  display.print(temp1,1);
  display.print(" H = ");
  display.println(humid1,1);
  //display.setCursor(0, 0);
  //  display.print("ST: ");
  //  display.print("T = ");
  //  display.print(SHT2x.GetTemperature(), 1);
  //  display.print(" H1 = ");
  //  display.println(SHT2x.GetHumidity(), 1);
  display.display();
}

void takeReadingsBME(float &temp1, float &humid1) {

  bme1.takeForcedMeasurement();
  temp1 = bme1.readTemperature();
  humid1 = bme1.readHumidity();
}

void takeReadingsSHT(float &temp2, float &humid2) {

  temp2 = SHT2x.GetTemperature();
  humid2 = SHT2x.GetHumidity();
}


texts: How to use while loop in arduino for infinte loop

texts:
I am doing code of esp while switching hotspot for connecting esp i am getting some problem .
I am using this line of code:

while ((!esp.find("WIFI ")) || (!esp.find("+CWJAP:3")));

but it is not working. Anybody please give me alternate how to use this type of looping.


texts: What's taking up so much RAM in an almost empty sketch?

texts:
I wanted to check how much memory (RAM) is used by an "empty" sketch. Here is my code:

int freeRam()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

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

void loop()
{
}

My result was that I have 1839 bytes of free RAM. I have an Arduino UNO, so there are 2048 bytes of RAM in total. Which means that 209 bytes are already taken. Wait, 209 bytes?! I started thinking and figured out that the Serial buffer must take some space. I've opened HardwareSerial.h and found this:

#if (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 16
#else
  #define SERIAL_BUFFER_SIZE 64
#endif

I've changed SERIAL_BUFFER_SIZE to 16 to see what will happen. (I've tried decreasing it to 1, but then the serial communication didn't work properly and I wasn't able to display the amount of free RAM). After this modification my result is 1935. So now "only" 113 bytes are taken. But what is taking this memory? HardwareSerial has 2 buffers:

struct ring_buffer
{
  unsigned char buffer[SERIAL_BUFFER_SIZE];
  volatile unsigned int head;
  volatile unsigned int tail;
};

ring_buffer rx_buffer = { { 0 }, 0, 0};
ring_buffer tx_buffer = { { 0 }, 0, 0};

So when the SERIAL_BUFFER_SIZE is 16 they take exactly 40 bytes. What is taking the remaining bytes (113-40= 73 bytes)? I'm aware that stack frames take some memory - calling main() which calls setup() whichs calls freeRam() probably take a few bytes, but 73 still seems too much.


texts:
Hello i am getting into Arduino and want to get my code tidy. I dont know how but thought by #include "Stepper.h" and "Servo.h" would work. The programm shows it works. But now it shows that i an expected inizializer before 'myservo' is missing. I dont know what is meant by this. Any help would be great!
Here is the code: the first one is the first tab the second the second tab and so on.
int stepsPerRevolution=2048;
int motSpeed=10;
int dt=500;
int buttonPin=2;
int motDir=1;
int buttonValNew;
int buttonValOld=1;
Stepper myStepper (stepsPerRevolution, 8,10,9,11);

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

#include "Servo.h"//einbezug der Dateien
#include "Stepper.h"

int menu = 0;
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:
//Displays the menu
  if (menu == 0) {
    //Prints the menu to the serial port
    Serial.println("Wähle eine Eingabe aus:");
    Serial.println("-----------------");
    Serial.println("1) Starte den Stepper Motor");
    Serial.println("2) Starte den Servo Motor");
    Serial.println("3) Stoppe alles");
    Serial.println("4) Trace Boundary");
    Serial.println("5) Start Drawing");
    Serial.flush();

    while (!Serial.available()) {}
    menu = Serial.parseInt();       // sucht für einen interger
    Serial.flush();
  }

The second where the problem is at line 8:
Servo myservo;
int pos =0;

void setup()
  // put your setup code here, to run once:
myservo.attach(3);  // attaches the servo on pin 9 to the servo object

}

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

for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(0);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(0);                       // waits 15ms for the servo to reach the position
  }
}

And the thrid tab in the programm:
int stepsPerRevolution=2048;
int motSpeed=10;
int dt=500;

int buttonPin=2;
int motDir=1;
int buttonValNew;
int buttonValOld=1;
Stepper myStepper (stepsPerRevolution, 8,10,9,11);

void setup()
  // put your setup code here, to run once:
Serial.begin(9600);
myStepper.setSpeed(motSpeed);
pinMode(buttonPin,INPUT);
digitalWrite(buttonPin,HIGH);
}
void loop()
  // put your main code here, to run repeatedly:
buttonValNew=digitalRead(buttonPin);
if (buttonValOld==1 && buttonValNew==0) {
  motDir=motDir*(-1);
}
myStepper.step(motDir*1);
} ```


texts:
I have 2 I2C devices that uses the same address. One of them is the DS3231 RTC. I use this library for the DS3231. I dont want to mess with the other one cause it is way more complicated then this one.:

#include <DS3231.h>

http://www.rinkydinkelectronics.com/library.php?id=73

Then, there is an object declaration for the real time clock:

DS3231  rtc(SDA, SCL);

I wounder if I can change that to:

DS3231  rtc(A0, A1);

I've seen the library but I haven't understand it yet (duh... I'm so stupid!). But is it possible to use an other pair of pins for I2C communication.

Note that I've already tried to use the soft I2C library but I really want to avoid it because it is just too much. If it is the final solution then so be it.


texts:
I am currently trying to control multiple LEDs with one Arduino Mega 2560 board. However, since each LED needs 3.6 volts and the board only supplies 5V I cannot make more than one light up.

Is there a way to increase to output voltage of the Arduino board ? Or perhaps of using arduino to turn on or off a battery that has a high enough voltage to power multiple LED ?

Thanks for your help


texts:
I'm relatively new at programming and many of the coding best practices I'm reading effectively state that there are very few good reasons to use a global variable (or that the best code has no globals at all).

I've done my best to keep this in mind, when writing software to make an Arduino interface with an SD card, talk to a computer and run a motor controller.

I currently have 46 globals for about 1100 lines of "beginner level," code (no line having more than one action). Is this a good ratio or should I look at reducing it more? Also what practices can I employ to reduce the number of globals further?

I'm asking this here because I'm specifically concerned with best practices for coding on Arduino products rather than computer programming in general.


texts: Erroneous sensor reading while connecting extra load

texts: I'm making a speedometer using arduino. I've made use of the interrupt pins to achieve the same. My problem is with the power source. I'm using a 12 V battery supply to power the arduino and I'm also using the same battery to use a horn. But, whenever I push the button to sound the horn, the IR sensor connected to the arduino is getting activated and I'm getting an erroneous reading. The only common thing between the arduino and the horn is the battery supply.


texts: I heard that using digital io pins in INPUT_PULLUP mode is much reliable and stable than in the case of using them in INPUT MODE.Then why is INPUT MODE still used...I mean Why isn't INPUT_PULLUP mode put as default ??


texts: Follow redirect of a captive portal with NodeMCU 0.9

texts:
What am I doing?

Trying to connect to a free wifi with a Nodemcu 0.9.

What I have already done?

Connecting and loading a test page in order to be redirected to the login page

Connection code:

 const char* ssid = "polimi";

  Serial.println("Attempting to connect");
  WiFi.begin(ssid);
  //Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

Detection of captive portal

  String host = "clients3.google.com";
  String site = "/generate_204";

  Serial.print("Connecting to ");
  Serial.println(host);

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  Serial.print("Requesting URL: ");
  Serial.println(site);

  client.print(String("GET ") + site + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  delay(500);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }
  Serial.println("");

  Serial.println("###Connection closed###");

What am I obtaining?

Nothing, but I wanted to obtain the html strings of the captive portal

What I'd Like

Find a way to follow the redirect and finally send a POST with my credential.


texts:
I have a GY-273 which has HMC5883L chip (I guess). I am trying to get data. I find a few codes and library (I don't have enough information about HMC5883L) but always all serial port screen there are only one value.
Here is my sketch:

#include <Wire.h>
#include "compass.h"

#define Task_t 10          // Task Time in milli seconds

int dt=0;
unsigned long t;
// Main code -----------------------------------------------------------------
void setup(){
  Serial.begin(9600);
  // Serial.print("Setting up I2C ........\n");
  Wire.begin();
  compass_x_offset = -48.23;  //122.17;
  compass_y_offset = 284.69;  //230.08;
  compass_z_offset = 59.87;  //389.85;
  compass_x_gainError = 1.07;  //1.12;
  compass_y_gainError = 1.09;  //1.13;
  compass_z_gainError = 1.01;  //1.03;

  compass_init(2);
  //compass_debug = 1;
  //compass_offset_calibration(3);

}

void loop(){

  t = millis();

  float load;

  compass_scalled_reading();

  Serial.print("x = ");
  Serial.println(compass_x_scalled);
  Serial.print("y = ");
  Serial.println(compass_y_scalled);
  Serial.print("z = ");
  Serial.println(compass_z_scalled);

  compass_heading();
  Serial.print ("Heading angle = ");
  Serial.print (bearing);
  Serial.println(" Degree");

  dt = millis()-t;
  load = (float)dt/(Task_t/100);
  Serial.print ("Load on processor = ");
  Serial.print(load);
  Serial.println("%");

  delay(100);
}

And Serial port screen is:

Gain updated to  = 1.22 mG/bit
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87

simulate this circuit – Schematic created using CircuitLab


texts: Force compiler to execute instructions sequentially?

texts: Is there a way to force the Arduino compiler to compile individual commands sequentially?  Looking at the disassembly, lines of the assembly code for different C/Arduino commands are mixed.  I was thinking something like a dmb or dsb command in ARM assembly.  I realize it's done the way it is for timing optimization, but I would like to see if changing it fixes some other timing issues I'm having.  I'm working on an Arduino Zero.  Thanks!


texts: How to share/Reassign analog pin for two Adafruit libraries for two adafruit hardware

texts:
I'm attempting to use the Adafruit BMP180 and Adafruit 16x2 RGB LCD Display together on the same Arduino Uno R1. Both the pieces of hardware and their libraries use Analog Pin 4 and 5. Is there any way to reassign the pins for one of the libraries so I can use both of the parts together?

Here are the libraries I am using:

Adafruit BMP180/BMP085:
https://github.com/adafruit/Adafruit_BMP085_Unified and https://github.com/adafruit/Adafruit-BMP085-Library

Adafruit 16x2 RGB LCD Display:
https://github.com/adafruit/Adafruit-RGB-LCD-Shield-Library


texts: Arduino car on bluetooth remote appears to crash when motors started

texts:
I built a Arduino robot car which accepts instructions via bluetooth. The instructions are pretty simple, they tell the car to stop, go forward, reverse, turn left or turn right.

When I have the car powered through the computer USB (ie when I have just uploaded the sketch), all works fine. However, when I run off independent battery power, the arduino seems to restart whenever I give the car an instruction which means the motors have to operate.

I know the sketch is restarting inside the Arduino because the blue tooth terminal displays the startup text which is inside the 'setup' function.

What is going wrong here? What issue am I encountering?

The board is an Arduino UNO with an Arduino Motor Shield attached. The blue tooth and two sonic sensors are attached to the motor shield pins.

Also, I have a 9V battery attached to the motor shield. Plus 4 times 1.5V batteries powering the UNO. Am I screwing up the power at all? Getting too much? Or too little?


texts:
I am trying to control an RGB LED strip with an Arduino. I have followed the tutorials in both of these websites:
Using MOSFETs: https://learn.adafruit.com/rgb-led-strips?view=all

Using LED Amplifiers: http://www.instructables.com/id/LED-Strip-Controller-w-LED-Amp-Arduino/

I have tried both setups and none of them work for me. When I try the setup with the MOSFETs, I am able to control each color but the blue LEDs are dimmer than the red and green, and therefore I can't mix any colors with blue.

When I try the LED Amplifiers, I am not able to control any light at all. Only the blue LEDs light up but the red and green dont. Also the blue LEDs stay ON the whole time and the only way to turn them off is to disconnect them from the DC power source.
What am I doing wrong?


texts:
I am facing for the first time with the ESP8266-01 module, so sorry if will write any stupid things.
I bought this module and I wanted to check its parameters through AT commands. Following some guide and wiring schemas found on the web I finally hook the ESP8266 up with an Arduino Uno (as in the picture below. The resistors are 220ohm each and the capacitor is 100uF) in order to print out to the serial monitor the AT commands and responses.
I uploaded the following code to Arduino Uno:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(6, 7);

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("Started");

  // set the data rate for the SoftwareSerial port
  esp8266.begin(57600);
  esp8266.write("AT\r\n");
}

void loop() {
  if (esp8266.available()) {
    Serial.write(esp8266.read());
  }

  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

But when I open the serial monitor (with both NL and CR selected and baud rate set to 9600) I got no response!!
If I try to send simple AT or AT+GMR commands, it returns to me nothing or random characters.
Does anyone please could tell me what I am doing wrong?


texts:
I'm trying to follow this tutorial here:

https://learn.adafruit.com/ttl-serial-camera/using-the-camera

Here's what my serial log is printing-- I've added a few commands for logging:

Arduino version is: 10605
Chip Select is: 4
VC0706 Camera snapshot test
Card failed, or not present

I know my SD card works because when I use this program: https://www.arduino.cc/en/Tutorial/ReadWrite

it works just fine. What am I messing up?

I'm using an arduino uno with wifi shield.

Thanks!


texts: button connection without connection to 5V pin

texts:
There are two types of tutorials for buttons:

I don't understand how a button on the first image works. Do we just hope that there is some non zero voltage and hope its enough? I think the first image is really bad, but can't explain why.


texts: Arduino Pro Mini is burned by 12v. Can I save it?

texts:
I have this Arduino Pro Mini clone (ATmega328) 5v.
I gave it exactly 12 volts through the RAW power input, but it instantly got hot and started fuming. Fumes were coming out of the area close to the black S4 thingy.
I don't know why, because I thought it can accept up to 12v through that input.
Now when I give it 5v only the middle led is lighting up and it's not connecting to the USB-UART interface anymore.
Is there any chance to save it?


texts: Second item in array not gets assigned from struct object, ArduinoJson

texts:
I got the below code generated this amazing tool.

const size_t capacity = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(4) + 2*JSON_OBJECT_SIZE(7);
DynamicJsonDocument doc(capacity);

JsonObject config = doc.createNestedObject("config");
config["type"] = "power_plug";
config["chip_id"] = "12345";
config["mac_address"] = "abc";

JsonArray config_attachments = config.createNestedArray("attachments");

JsonObject config_attachments_0 = config_attachments.createNestedObject();
config_attachments_0["name"] = "socket";
config_attachments_0["input_type"] = "toggle_switch";
config_attachments_0["on_state"] = "on";
config_attachments_0["off_state"] = "off";
config_attachments_0["pin_type"] = "output";
config_attachments_0["pin"] = 15;
config_attachments_0["current_state"] = "on";

JsonObject config_attachments_1 = config_attachments.createNestedObject();
config_attachments_1["name"] = "socket_1";
config_attachments_1["input_type"] = "toggle_switch";
config_attachments_1["on_state"] = "on";
config_attachments_1["off_state"] = "off";
config_attachments_1["pin_type"] = "output";
config_attachments_1["pin"] = 12;
config_attachments_1["current_state"] = "off";

serializeJson(doc, Serial);

This prints out the desired json properly. but when amend single line from the second array item, to take the on_state from my struct object d_config,

Serial.println(">>" + d_configs.peripherals[1].current_state);
Serial.println(">>" + d_configs.peripherals[1].on_state);
config_attachments_1["on_state"] = d_configs.peripherals[1].on_state;

the parsing gets quiet unexpected, and some of the keys from serialised string json gets missing. For above case, This gets printed in serial monitor;

>>off
>>on
{"config":{"type":"power_plug","chip_id":"12345","mac_address":"abc","attachments":[{"name":"socket","input_type":"toggle_switch","on_state":"on","off_state":"off","pin_type":"output","pin":15,"current_state":"on"},{"name":"socket_1","input_type":"toggle_switch","on_state":"on","off_state":"off","pin_type":"output","pin":12}]}}

NOTE in the second item of attachments, the key current_state is entirely missing.
When I assign all values from this struct object, the serialised json misses many more keys... and the behaviour is quite unexpected. here is how I have defined my structs;

typedef struct Peripheral{
    String name;
    String input_type;
    String on_state;
    String off_state;
    String pin_type;
    String current_state;
    int pin;
};

typedef struct {
  String type;
  String chip_id;
  String mac_address;
  Peripheral peripherals[10];
} DeviceConfig;

I am not sure if its an issue during serialization or something else... :/
Any help would be highly appreciated :) .

UPDATE When I added three items inside attachments, then the serialized json string is missing some keys for only the last item. Seems like only the last item on the list is having problem getting serialized.


texts: Determining power consumption with Arduino and JeeLib

texts:
I built a basic LED blinker to serve as a car theft deterrent. Originally I was using a 9V battery and delay() but I've refined my approach to consume less power. Here's my code, utilizing the JeeLib library:

#include <JeeLib.h>

int led = 13;
ISR(WDT_vect) { Sleepy::watchdogEvent(); }

void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

void loop() {
  blink_quick();
  blink_quick();
  Sleepy::loseSomeTime(8000);
}
void blink_quick() {
  digitalWrite(led, HIGH);
  Sleepy::loseSomeTime(250);
  digitalWrite(led, LOW);
  Sleepy::loseSomeTime(250);
}

It just blinks twice every 8 seconds. I also used 4 AA batteries as they have a higher amperage rating. How long should this system work before I need to replace the batteries?

My thinking is that AA batteries offer 2000mAh and an Arduino typically consumes about 45mA on average. If I were running the above code with delay() instead of the JeeLib functions, it would last for 44 hours. Let's call one cycle the two blinks and the following 8 seconds of rest. I am confused about how long I should factor in for the digitalWrite(led, HIGH) and the corresponding 'low' call, because the rest of the time, the circuit is using JeeLib. I am just interested in figuring out how long I can let this run without changing the batteries, and admittedly I am not experienced enough to tell definitively.

Thanks!


texts:
im sending string data via serial with following format ex. :45:60 or such as ":120:57".i got the data shown in Serial.println (secondValue) Serial.println (thirdValue); but i cant convert it to int

String myString;
char c;
int Index1,Index2,Index3, azi;
String secondValue, thirdValue;
void setup(){
Serial.begin(9600);}
void loop(){
while (Serial.available()>0)
{
delay(10);
c = Serial.read();
 myString += c;
}
 if (myString.length()>0)
{
Index1 = myString.indexOf(':');
Index2 = myString.indexOf(':', Index1+1);
Index3 = myString.indexOf(':', Index2+1);

secondValue = myString.substring(Index1+1, Index2);
thirdValue = myString.substring(Index2+1, Index3);

Serial.println(secondValue);
Serial.println(thirdValue);

myString="";
}
delay(1000);
}


texts:
I've got a microSD module adapter from the far east, and so far so good, and although it can create files using writeFile, it does not append messages. It returns true, i.e: message appended successfully but when you read the file on the computer or when ESP32 reads on reboot, it's blank.
This is how I call the function:
char* sdFileName = "/v.ea";
if (appendFile(SD, sdFileName, "Heyy")) {
//success
} else {
//failed
}

This is the modified, appendFile function:
bool appendFile(fs::FS &fs, const char * path, const char * message) {
  bool appendSuccess = false;
  if (DEBUG == 1) {
    Serial.print("Appending to the file: ");
    Serial.println(path);
  }
  File file = fs.open(path, FILE_APPEND);
  if (!file) {
    appendSuccess = false;
    if (DEBUG == 1) {
      Serial.println("Failed opening the file.");
    }
  }
  if (file.print(message)) {
    appendSuccess = true;
    if (DEBUG == 1) {
      Serial.println("Appended succesfully.");
    }
  } else {
    appendSuccess = false;
    if (DEBUG == 1) {
      Serial.println("Appending failed.");
    }
  }
  file.close();
  if (appendSuccess) {
    return true;
  } else {
    return false;
  }
}

I've even tried the writeFile function with file.seek(EOF) but no luck.
When calling appendFile for the first time, this appears:
[W][sd_diskio.cpp:149] sdCommand(): token error [17] 0x17
Appending succesfully.

When the appendFile is called for the second time, this appears in serial monitor:
[W][sd_diskio.cpp:149] sdCommand(): token error [17] 0x17
[W][sd_diskio.cpp:149] sdCommand(): token error [17] 0x5
[W][sd_diskio.cpp:149] sdCommand(): token error [17] 0x5
[E][vfs_api.cpp:265] VFSFileImpl(): fopen(/sd/v.ea) failed
Appending failed.

I am using two SPI devices: MFRC522, and before calling SD's functions, I do a digitalWrite(SD_SS, LOW) to "enable" the SD functions till it completes its operations and returns back to HIGH to disable it.
The example in SD(esp32) works fine - writing, appending, deleting, renaming, etc. all work well.


texts: Control/Interacting with Android OS using Arduino board

texts:
I am new to arduino, and based on my search, it is possible to connect Android devices and Arduino board thru bluetooth module. But most solutions i found are either for controlling Arduino board using an Android app, or controlling Android app using Arduino board.

My question is, is there a way to control/interact with the Android OS on the phone using Arduino, thru whatever connection?

I am asking this because I am thinking of building a portable keyboard or touchscreen device for Android devices, and want to see if Arduino is a good platform for prototype.


texts: Arduino Code for Pulse Skip Modulation (PSM)

texts:
I have recently bought this light dimmer, and only when I received it I noticed it works with PSM (Pulse Skip Modulation) and not PWD (Pulse Width Modulation).

Does anyone know how to write Arduino code and do the wiring for this dimmer? I can't seems to find a working example.

Thanks


texts: Which arduino should I start on to learn about it?

texts: I'm pretty interested in arduino and the things I can learn from it. Being that I'm new into this I wanted to know which model I should get that would be easiest to learn on and why. What does this model come with, how much, and reputable place where one can purchase this.


texts: nRF24L01 : transmission fail when receiver is connected in Serial

texts:
I have two Arduino Nano communication with radio.
One is a transmitter and send simple message :

#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

//RADIO RF24 PINS
#define RF_CE    7
#define RF_CSN   8

//Radio
RF24 radio(RF_CE,RF_CSN);
const byte address[6] = "00001";

//Communication structure
struct Data {
  long type;
  float value;
} data;

/**************************************************************************/
/*
    Displays some basic information on this sensor from the unified
    sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/

void initRadio() {
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPALevel(RF24_PA_MIN);
  radio.openWritingPipe(address);
}

void setup() {
    Serial.begin(9600);
    // Set delay between sensor readings based on sensor details.
    initRadio();
}

void sendMessage(long type, float value){
  Serial.println("sendMessage");
  data.type = type;
  data.value = value;
  if(radio.write(&data, sizeof(Data))){
    Serial.println("Send SUCCESS");
  }else {
    Serial.println("Send FAIL");
  }
  delay(100);
}

void loop() {
  // Delay between measurements.
    delay(1000);

    sendMessage(0, 20.10);
    sendMessage(1, 45.3);
    sendMessage(2, 1033);

}

The other is a receiver and get the message from the transmitter Arduino and send message with Serial via USB to a computer :

#include <SPI.h>

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

#include <ArduinoJson.h>

#define RF_CE    7
#define RF_CSN   8

//Radio RF24
RF24 radio(RF_CE,RF_CSN);
const byte address[6] = "00001";

//JSON
const int capacity = JSON_OBJECT_SIZE(8);

//Communication structure
struct Data {
  long type;
  float value;
} data;

long previousMillis = 0;
long interval = 3000;
bool refresh = false;

void sendValue(String source, String type, float value) {
  DynamicJsonDocument doc(capacity);
  doc["type_message"] = "measure";
  doc["source_id"] = source;
  doc["value_type"] = type;
  doc["value"] = value;
  Serial.write(0x11);
  serializeJsonPretty(doc, Serial);
  Serial.write(0x12);
  Serial.println("");
  doc.clear();
}

void initRadio() {
    radio.begin();
    radio.setRetries(15, 15);
    radio.openReadingPipe(0, address);
    radio.setPALevel(RF24_PA_LOW);
    radio.startListening();
}

void readRadio(){
  if(radio.available()){
    while(radio.available()) {
      radio.read(&data, sizeof(data));
      Serial.print("type:");
      Serial.print(data.type);
      Serial.print("value:");
      Serial.println(data.value);
      sendValue("remote", "test_radio", data.value);
    }
  }
}

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

void loop() {
  // put your main code here, to run repeatedly:
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;
    float humidity = 45.60;
    float temperature = 21.30f;
    sendValue("local", "humidity", humidity);
    sendValue("local", "temperature", temperature);
  }
  readRadio();

}

The issue that I have is that when I connect my computer via the Serial port COM to the receiver, every radio message sent by the transmitter fail. But before I connect to the receiver, the messages sent by the transmitter are in success.

I don't know what can cause this issue.


texts: What do I do about a compiler error " variable 'font' must be const"

texts:
I am trying to run the test program from Adafruit, with their libraries, for an Arduino controlling a Nokia5110 display and get this error message:

Arduino: 1.5.8 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"

    /home/Harry/Arduino/libraries/Adafruit_GFX/glcdfont.c:9:23: error: variable 'font' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char  font[] PROGMEM = {
                           ^
    Error compiling.

Please can anyone explain this? I can happily give more details, but I am not yet sure how much is needed and the files are rather too long to include them all at this stage.


texts:
I would like to detect signals in nanosecond scale. For that, an ADC with at least 500 MSPS is required.

My question is if its possible to use an external ADC with 500 MSPS with a 16MHz Arduino Mega? If not, is there any additional hardware like FIFO buffer to overcome this problem?

Please help, thanks!


texts: Input audio from jack to Arduino, and output by

texts:
I've never used Arduino but I know a few of its utilities.

I want to input audio from a Jack cable (analog) and be able to send it via Bluetooth, or Wi-Fi, or USB to an Android Phone and being able to print the values (from 0 to 1).

I'm looking for tutorials but I just find the way to make the input but not the output.

Which one would you recommend me of Bluetooth, Wi-Fi and USB?

Thanks.


texts: I have recently brought an arduino nano. It has only two ground pins but I needed three for my project. Is there a way to use a digital or analog pin as ground pin? Please show me how to do it


texts: Follow up question to Calling a timer when a button is pushed

texts:
I have changed the code with some help here. There are two buttons each one is set to turn on a LED. When the LED turns on it is timed and when the time is up it turns off. The problem I am having is that only one LED can be on at a time even though I am not using the delay() and I am using millis() to keep track of time. So if I press button one the first LED will turn on. Even if I press button two at this time the second LED wont turn on until the first one turns off.

const int ledPin2 = 2;
const int ledPin3 = 3;
const int buttonPin6 = 6;
const int buttonPin7 = 7;

const unsigned long onTime = 10000;
unsigned long previousMillis = 0;

void timer() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin2, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin2, LOW);
}

void timer2() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin3, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin3, LOW);
}

void setup() {
Serial.begin(9600);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(buttonPin6, INPUT);
pinMode(buttonPin7, INPUT);

}

void loop() {

int buttonState2 = digitalRead(buttonPin6);
if (buttonState2 == HIGH) timer2();

int buttonState = digitalRead(buttonPin7);
if (buttonState == HIGH) timer();

}


texts:
I want to easily send a number from a phone to my esp8266.
I have an app that sends the number in the format IP/number.
How can I modify the code to give my the number behind the IP address as an integer?

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;

// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

ESP8266WebServer server(80);

String webPage = "";

void setup(void){

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (mdns.begin("esp8266", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }

  server.on("/", [](){
    Serial.println("device connected");
  });
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

So it would do something like this for and should be looking through every i between 0 and 200. :

server.on("/"+String(i), [](){
    Serial.println("i");
  });


texts: Arduino Interrupts Classes and Namespace

texts:
I'm working inside the Arduino IDE environment and have made a class that builds on the Adafruit RDG LCD with interrupts While looking at how to combine the Attach Interrupt() into my class I came across this post about using namespaces

Why make a class then? What about a namespace?
A class with one instance is like a group with one person in it.
-nickgammon

Understanding that Mr.Gammon is kind of a big deal around these parts, I'd like to understand how to insert/alter my current class into a namespace format. Currently, the most in-depth tutorial I've found is here, but I don't see how I would mix in the Attach Interrupt() function
Right now, my code looks like
/**** Pre-Setup *****/
#define Menu_PIN 3
voltile bool flag;

//Init Class
class LcdMenu : public Adafruit_RGBLCDShield
{
  public:
  MenuFoo()
}
LcdMenu LcdM;

//run Setup
void setup()   /****** SETUP: RUNS ONCE ******/
{
  pinMode(Menu_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(Menu_PIN), ProcMenu, FALLING);
}

void loop()
{
  if(flag){
    LcdM.MenuFoo();
    flag=false;
  }
}

//Handles Inturrupts for Class
void ProcMenu()
{
  flag=true;
}

//define MenuFoo
void LcdMenu::MenuFoo(){[code]}

As I understand it, Implementing a namespace would eliminate the need for the ProcMenu() function making my code easier to read/maintain.


texts: I connect my Bluetooth hc-05. But the blind led in the Bluetooth module is not stable when I connect with my Android phone. Help help me to solve this.


texts: How do you make a Class variable array bigger?

texts:
I am making an infrared macro-keyboard, I want to store Unicode for the Keyboard class in an array inside a class I made called Keybindand to allow the user to program as many outputs as they want, I want the storage to be mutable.  I currently use the String class and decode within the program but it's cpu intensive and not very practical.
I want to use an array or list, but I haven't found any way to expand the size of an array inside a class.  Casting a temporary array didn't work:

  int intArray[] = {0,1,2,3,4,5};
  int* temp[7];

  for(int x = 0; x<sizeof(intArray)/sizeof(intArray[0]); x++){
    temp[x] = intArray[x];
  }
  temp[6] = 6;
  intArray = temp;

IDE spits out "incompatible types in assignment of 'int* [7]' to 'int [6]'"


texts: Feasibility of project with 50 leds working independently

texts:
I don't have much knowledge in Arduino and I'm about to start a new project which I believe can be done with it.

There will be 50 boxes with a led in top of each one. The user will type a number in a keyboard (1 to 5 for example), and then based on a table, the leds according to that number should light up.

It will have some overlaps, for example, Number 1 would light led 1, 2 and 3, while Number 2 would light leds 1, 2, 3 and 4.

Could I build such a project with arduino? Or are there too many inputs/outputs (keyboard, 50 leds)? I was thinking to buy an Arduino Uno to start learning, but first I'd like to know if it's feasible.

Thanks already


texts: How to keep amperage in serial and parallel?

texts:
I have a 2000mA AC adapter and also I have the lights that I show here:

Each of these lights consume up to 300mA.

If I make a circuit with 3 lights in serial, ¿will the amperage of each light decrease?

If I make a circuit with 3 lights in parallel, ¿will the amperage of each light decrease?

I am asking it because I don't want the lights to decrease the luminosity. I want the maximum luminosity in each light.

The lights are for growing lettuces. Now I am using a low consumption light but are not efficient:


texts: Controlling EL wire or panels with arduino

texts:
I understand that el wire and paper needs a special power source known as an inverter to light it up.

If I wanted to control it from an arduino, what point would I connect the arduino to the light or inverter?


texts: How to pass input value from webpage form to Arduino code

texts:
I am trying to pass number from web server Arduino using input form, into SPIFFS file, using script.
Here is webpage code.
void handleRoot() {
  if (server.hasHeader("Cookie")) {
    //   Serial.print("Found cookie: ");
    String cookie = server.header("Cookie");
    //   Serial.println(cookie);
  }
    if (server.arg("target")) {
      server.sendHeader("Location", "/");
      server.sendHeader("Cache-Control", "no-cache");
      server.sendHeader("Set-Cookie", "ESPSESSIONID=1");
      server.send(301);
      //  Serial.println("Log in Successful");
      return;
    }

 <form action="http://192.168.4.1/get" method="POST">;
 <input id="target" type="number" name="target"  required/>;
 <input type="submit" value="Start" name="SUBMIT"/>;
 </form>;

here is IDE code;
File fw = SPIFFS.open(filename, "w");

    if (!fw) {
     Serial.println("Error opening file for writing");
      return;
    }
    int numBase = target;
    char Written = fw.print(numBase);
    fw.close();

Anyone can help me, please let me know, what part of my code, I'm doing wrong?
Thanks in advance.


texts: Connect Bluetooth remote control with Arduino

texts:
For a project I need to connect a Bluetooth Remote control with an Arduino Nano.

On the Arduino-side I have an HC-05-Bluetooth module. With the Android Application "Bluetooth Terminal" I can verify that the connection is ok, because I can send and receive Strings with an Android smartphone.

In the minimal example I send values from a sensor which is connected to my Arduino via bluetooth to the smartphone, which is working nice. So I guess the wiring is correct:

void loop() {
  sensorValue = analogRead( sensorPin );
  cm = 10650.08 * pow( sensorValue, -0.935 ) - 10;
  Serial.println( cm );
  softSerial.println(cm);
  delay( 500 );
}

Instead of sending sensor values, I need to connect said remote with the Arduino.

(Picture shows the basic model of said remote control.)

The remote control has the Bluetooth class 20258C which means:

Major Device Class: Peripheral
Limited Discoverable Mode
Audio
Pointing device
Remote control

Remote Control Bluetooth  Specifications:

BT Device Name: YL-BTM3-xxxxxx
Supplier ID and Product ID: 0x0A5C / 0x4503
Class of Device: 0x20258C

My Question is: How can I pair those two devices? I can get the remote control into "Pairing mode", by pressing 2 Buttons. But how do I pair the Arduino-Bluetooth-module with this remote-control? Is it possible at all?

Best regards


texts: SIM900/Arduino UNO R3 serial communication not working

texts:
For some reason I cannot establish serial connection between the two devices. The shield is connected to the network because my number can be called, but I cannot send it any commands via the serial.
I tried several ways to wire it up:
shield rx&tx (the ones that require female jumper) to 7 & 8 of arduino, declaring 7 & 8 in the serial.
shield pins 7 & 8 (they have (serial) as label) to 7 & 8 of arduino, declarting 7 & 8 in the serial.
shield rx&tx the little holes to 7 & 8 of arduino, declaring 7 & 8 in the serial.
Tried even different pins other than 7 & 8. None worked.
I'm powering the shield with 12v transformator that can provide up to 3Ah and the arduino is connected to laptop.
Any suggestions ?
Here's the code:

#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

void loop()
{
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.


texts:
I have an Arduino setup from which I can control my RGB LED strip from my computer using LAN.
It worked like a charm in the start, but after two days, my Ethernet Shield W5100 for Arduino Uno stopped working, and I can't figure out why.
When I connect the Ethernet Shield, the red LED "pwr" is solid red and the "FULLD" flashes orange every second.
The setup:
I have followed an Adafruit guide, connecting the Arduino as such:
On top of the Arduino, I have the Ethernet Shield. All this is powered by an 12V/4A power supply connected to the Arduinos 2.1mm jack.
As I said, this setup worked fine for a few days. While it was on, I noticed the Arduino getting somewhat hot, but some google searches assured me that Arduino Uno can handle high temperatures, so I did not pay any attention to it.
The LED strip is not too long - about 2 meters with about 150 LEDs.
What I have tried:

When I detach the Arduino from my breadboard, the Ethernet Shield
will still not connect
I have tried connecting the Shield to another Power Supply (Computer USB) using another Arduino, but the Shield would still not connect.
I have added a debugging Serial.print message in the Arduino loop function. When using serial monitor, this message is printed over and over again (as if it is stuck in a reset loop)
I have verified for MAC address collisions, even changed the MAC address of the Shield multiple times.

Have I somehow burned the Ethernet Shield? Why won't it work anymore?


texts: Which Bluetooth Module can I use with Arduino Micro/Mini?

texts:
I need to use a Bluetooth module with an Arduino Micro/Mini.

Please suggest which one would be the best, HC 05/06, or any other?


texts:
Unable to flash Arduino when TXD pin of HC-6 Bluetooth module is connected to Arduino RXD pin?
I get the following error:

Flashing with command:C:/Users/home/.arduino-create/arduino/avrdude/6.3.0-arduino9/bin/avrdude.exe -CC:/Users/home/.arduino-create/arduino/avrdude/6.3.0-arduino9/etc/avrdude.conf -q -q -patmega328p -carduino -PCOM4 -b57600 -D -Uflash:w:C:/Users/home/AppData/Local/Temp/arduino-create-agent051272951/sketch_jun10a.hex:i
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48


texts:
I try to switch on/off IKEA Ledberg LEDs which are powered with 24 V using the setup from this tutorial video: https://www.youtube.com/watch?v=sVyi7yWuXxs

I use a IRLB8721PBF MOSFET. When I switch the output from HIGH to LOW the LEDs shine a little less brighter. When the pin is set to HIGH I can measure 23,4 V at the LEDs and when it's set to LOW I measure 22,9 V.

So the MOSFET is not really switching off but why? I also tried to put a 100 kOhm resistor between Gate and Source which also did not help.

Do you have any hints for me?

Cheers,
Oliver


texts: Nano v3 dual power source use & detection

texts:
I would like to run a Nano 3.0 from both the VIN (mains power supply 7V) and USB power (backup). I understand it selects the highest voltage and switches to VIN at 6.6V. However I am unsure of the following:

How is it possible to detect which power source is being used?
How is it possible to detect if the source has been switched?
How is it possible to detect if the power source NOT in use has been disconnected.


texts:
I am new to Arduino and programming and I am muddling along with some tutorials, I have a little project I am working on. It's basically an LCD screen with 5 buttons, a simple menu system that will control some stepper motors.

Now I have been able to both program and run the LCD from the Arduino and program and run the stepper motors. This was pretty straightforward due to the abundance of information. Now due to the small number of inputs on the Uno I knew I would need to expand on these so I bought some MCP23017 I/O expander chips.

Setting up the LCD on the MCP23017 was easy enough again due to the lots of tutorials and libraries, but I just cannot figure out how to work a stepper motor via the MCP23017. I am using 28BYJ-48 stepper motors and ULN2003 stepper driver boards. Yes I know cheap and nasty but they are fine for my task.

So I am basically looking for a little help on how to run stepper motors through the MCP23017 chips. I have the wiring and connections set up, just need some help on the programming.


texts: Formula to calculate energy required to power an Arduino board

texts:
Given an Arduino board with the following specs:

ATmega328 Arduino Nano AVR® ATmega MCU 8-Bit AVR Embedded Evaluation Board (link)

What is the mathematical formula to calculate how much energy/power would be required to keep the Arduino board on (meaning in "standby" mode, therefore not consuming any energy but the one required to keep it "alive")?

Please note I am new to all things electronics, Arduino but most importantly physics and maths. Thank you.


texts: code for OLED display suddenly crashes arduino Nano

texts:
Today i've been playing with my monochrome oled 128x64 adafruit screen. I've got it connected using SPI. Previously today i had no problems att all and i was able to print messages and variables on the screen. But suddenly my functions causes the arduino Nano to restart and initialise Setup() again!
It is very frustrating and i cannot figure out what part of my code is causing the crash!
I have tried running the adafruit example code to test the screen and it is working, so the screen is not broken and the wires must be correct.

Here is the code for my display:
display.h :

#include <Adafruit_GFX.h>  // Include core graphics library for the display
#include <Adafruit_SSD1306.h>  // Include Adafruit_SSD1306 library to drive the display

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Define SPI pins:

#define OLED_MOSI   9
#define OLED_CLK   6
#define OLED_DC    7
#define OLED_CS    8
#define OLED_RESET 13

// Create display
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
  OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

#include <Fonts/FreeMonoBold12pt7b.h>  // Add a custom font
#include <Fonts/FreeMono9pt7b.h>  // Add a custom font

void initDisplay(){

  delay(100);

  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();  // Clear the buffer

  display.setTextColor(WHITE);  // Set color of the text

  display.setRotation(0);  // Set orientation. Goes from 0, 1, 2 or 3

  display.setTextWrap(false);  // By default, long lines of text are set to automatically “wrap” back to the leftmost column.
                               // To override this behavior (so text will run off the right side of the display - useful for
                               // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored
                               // with setTextWrap(true).

  display.dim(0);  //Set brightness (0 is maximun and 1 is a little dim)

  Serial.println("Display initiated..");

}

void printMessage(String message){
  display.setFont(&FreeMono9pt7b);  // Set a custom font
  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0
  display.setTextColor(WHITE);
  display.setCursor(0,50);
  display.clearDisplay();
  display.print(message);
  display.display();
  Serial.println("printing message on display");
  delay(1000);

}
void printTemp(long temp){

  display.setFont(&FreeMono9pt7b);  // Set a custom font
  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0

  display.clearDisplay();  // Clear the display so we can refresh
  // Print text:
  display.setCursor(25, 15);  // (x,y)
  display.println("temp:");  // Text or value to print
  // Draw rectangle:
  display.drawRect(79, 0, 35, 27, WHITE);  // Draw rectangle (x,y,width,height,color)
                                           // It draws from the location to down-right

  display.setFont(&FreeMonoBold12pt7b);  // Set a custom font
  // Print variable with left alignment:
  display.setCursor(83, 20);  // (x,y)
  display.println(temp);  // Text or value to print

  display.display();  // Print everything we set previously
  Serial.println("Printing temp..");

}

main.ino:

#include "display.h";
#include "DHT.h";
#include "Radiocom.h";

long temperature;

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

  initDHT();
  initDisplay();
  //initRF();
}

void loop()
{
  //temperature = readTemp();
  //delay(1000);
  //printTemp(temperature);
  String message = "123456789abc";
  printMessage(message);
  //sendMsg();
  //RFlisten();
  delay(1000);
}

If anyone can help me out in any way, i would be really thankfull!


texts: SIM800L module just repeating data sent via serial

texts:
I've got a Teensy 2.0 with simple AltSoftSerial as displayed on image:

As you can see, when I send a command (or any other input via serial) the SIM800L module sends me the same input. I tried to switch the TX and RX wires on the module (in case I misconnected them), but then it returns nothing. When I connect the TX and RX wires directly to each other I've got the exact same result as if they are connected to the module.

The whole thing is connected in this way - computer is connected via USB to teensy, the SIM800L and Teensy are connected via software serial (RX to TX and TX to RX), the SIM800L module is powered from an external battery (it requires specific voltage between 3v4 and 4v4).

Is the module bad, or is it a wrong wiring? Why is the module not communicating and just returning what I sent to it?

EDIT 1:

I'm not particularly looking for mistakes in code, the code is most likely correct. I think the problem is probably somewhere around the SIM800L module.

The module shouldn't just repeat what it got, but it should replay with something like OK, or other answers.


texts:
Here in figure,  we can see two waveforms.

Below one is waveform of raw RPM signal. I want to find square waveform which based on that LOW INTERVAL of RPM signal and length must vary according our requirement. So for that purpose, I just made inverter circuit using 74HC14 and Low pass filter(for removing noise).

As a result of that circuit, I got Upper one waveform means square wave signal. Now, you can see it has also one spike beside square wave(I don't want that). And I can't vary length because inverter circuit gives only perfect inverting signal.

Is it possible to make square wave like this and also vary the length of that square wave with help of Arduino?

Here, I want to use Arduino because I have to vary the length of square wave with help of programming.  For example, if I want 10ms square wave then just enter value 10 in programming then generate 10ms square waveform. Rising edge must be same. And right now, I have no clue or idea how to do this.

If possible then please give me some suggestion how to do this.


texts:
Finally got around to playing with my uno today for the first time. ( It's a branded sunfounder UNO R3)

First project. Simple blink. Using arduino 1.6.3, Windows 8.1 It is hooked up correctly.

void setup() {
   // initialize digital pin 13 as an output.
   pinMode(9, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
   digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(10000);              // wait for a second
   digitalWrite(9, LOW);    // turn the LED off by making the voltage LOW
   delay(10000);              // wait for a second
}

What I get is a fast blinking LED. I've tried multiple values and it doesn't change. No error on upload.
I've commented out everything except the digitalWrite(9, HIGH); and I get a fast blink.

I tried:

void loop() {
   digitalWrite(9, LOW);
   delay(5000);
   digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
}

And I get nothing, it doesn't even turn on.

Same if I remove the first digitalWrite();

So, I'm already a little lost here. I did a but of google searching tried adding a serial 9600 line, and a few other things. Nada.


texts: WizNet chip on Ethernet Shield oddly hot

texts: I'm making a thermometer and, so I can graph the data, I have an Uno with the WizNet shield sending the data to a LAN ip. The chip itself is oddly hot, its temperature measures at around 110-120ºF (43.33-48.89ºC). I want the program to be running almost 24/7. Is it okay for the chip to be this hot?


texts: How to control 6 stepper motors with Arduino?

texts:
I would like to control 6 stepper motors (0.225A, 2 V) with Arduino. I was thinking to use motor drivers from Pololu website, for example DRV8834.

Is it possible?

Any suggestion for another type of motor driver?

We need to limit the current, but I also got the advice to use the PWM signal to control the stepper motor. Any advice for this?


texts: arduino I2C maximum number of writes per Transmisson

texts: Is there any limit on the number of Wire.write() commands consecutively in between the Wire.beginTransmission() command and the Wire.endTransmission() command for the Arduino Wire library?


texts: Why all blink tutorials use 330 ohm resistor

texts:
When I do the led calculation I found 150 ohm resistor is enough for 3mm red led. If so why all arduino tutorials, like this one, are suggesting 330 ohm resistor?

I assume V = 5 Volt, diode forward voltage = 2V and diode forward current 20mA


texts:
The Code Below now works:

void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  //Serial.write(cmd[i]);
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

Input is a series of ASCII-encoded hex digits and getting the output to print the byte values of the hex.


texts: How to drive motors and use an ultrasonic sensor simultaneously?

texts:
I have a L298 motor driver, which I coded with an Arduino Nano.
The code is very simple at the moment:

// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;
void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  Motors_FWD_PWM_Initialize();

  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  MotorsOff();
}
void loop()
{
  demoTwo();
  delay(1000);
}

void Motors_FWD_PWM_Initialize()
{
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
}

void MotorsOff()
{
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}

Currently I have two questions:

Q1: I have an ultrasonic sensor, how can I write the code so that the motors work and 'keep an eye out' with the ultrasonic sensor simultaneously? i.e. When a certain proximity is reached I would like the robot to stop.

Q2: Also I would like my robot to 'rove' around. How can I make it so? I was thinking having a number of subroutines, and making the arduino randomly choose one.


texts: How to get elapsed seconds since Jan 1, 1970?

texts:
I am building a time-critical system using Arduino. Is there any way to get the elapsed seconds like time.h of C in Arduino? I tried time(NULL) but it returns 0. Then moved forward to use now() in Time.h. But the result persists.

How can I get the elapsed seconds since Jan 1, 1970 until now?


texts:
Sorry if this is a newbie question, but I'm really struggling with this and I can't seem to figure it out.
I've been learning Arduino for a while, and for my next project I'm attempting to build a drone. When I tested the motors that I purchased before, they seemed to work fine using the PWM pins and I saw no need for a motor driver.
However, now, a week later, the PWM pins are much too weak. I've set them to OUTPUT mode and HIGH.
Should the basic digital output pins be able to run fairly small drone motors like mine?
Thank you for your help! :)


texts: Conditions with GSM module SIM900 doesn't execute

texts:
I'm executing this code to control a LED with GSM SIM900 message but there are two problems. First, it receives messages sometimes and some times doesn't. The second is that it doesn't execute the if conditions that are on the GSM message when received.

Is there a problem with my GSM module? Can any one help?

#include <SoftwareSerial.h>
SoftwareSerial gsm(9,10);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }

  while(gsm.available() > 0)
  {
    Serial.write(gsm.read());
  }
  if ( msg == "ON")
  {
    Serial.println("ON");
    digitalWrite(LED, HIGH);
     Serial.println("ON1");
    delay(1000);
  } else if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
  if(msg != "") msg = "";
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 msg = "";
 while(gsm.available() > 0)
 {
  msg += gsm.read();
 }
 Serial.println(msg);
}


texts: How to dynamically set pinMode and dynamically write value to pins in Arduino using arrays?

texts:
I am trying to create a library called "LED" for LED Sequencer in Arduino IDE,where the user has to configure the LED pins using an array and pass it to  LED constructor in program and then will be able to use BlinkAll(),LeftToRight() and RightToLeft() Functions which lights the LED from Left to Right or Right to Left based on the sequence mentioned in the array. The problem is when I initiate the array and pass it to the constructor Pins 4,5,7 are not working at all , Please help me find what is the possible issue
the code in LED.cpp file is shown below

#include <Arduino.h>
#include "LED.h"

LED::LED(int channel, int* a){
  _channel = channel;
  for(int i = 0 ; i < channel; i ++)
  {
    _pins[i] = a[i] ;
    pinMode(_pins[i],OUTPUT);
  }
}
void LED :: BlinkAll(int delay_ms)
{
   for (int i = 0 ; i<_channel;i++)
   {
    digitalWrite(_pins[i],HIGH);
   }
   delay(delay_ms);
   for (int i = 0 ; i<_channel;i++)
   {
    digitalWrite(_pins[i],LOW);
   }
   delay(delay_ms);
}
void LED :: LeftToRight(int numberofLEDs, int delay_ms)
{
  for(int i =0 ;i<_channel; i++)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i =0 ;i<_channel; i++)
  {
//    if (i > 0)
//    {
//     digitalWrite(_pins[i-1], LOW);
//    }
  for(int i =0 ;i<_channel; i++)
  {
    digitalWrite(_pins[i], LOW);
  }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}
void LED :: RightToLeft(int numberofLEDs,int delay_ms)
{
    for(int i =_channel ;i>0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i = _channel ;i>0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i+1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

LCD.h

#ifndef LED_h
#define LED_h

#include <Arduino.h>

class LED
{
public:
  LED(int channel, int* pins);
  void BlinkAll(int delay_ms);
  void LeftToRight(int numberofLEDs, int delay_ms);
  void RightToLeft(int numberofLEDs, int delay_ms);
  void BlinkAlternate(int delay_ms);
private:
  int _channel;
  int _pins[16];
};

#endif

Sample Code

#include "LED.h"

int const LED_pins[8]={5,6,7,8,9,10,11,12};
int const No_of_LED = 8;

LED led(8,LED_pins);

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  led.LeftToRight(1,500);
  led.RightToLeft(1,500);
}


texts:
I am trying to upload an empty program on the Adafruit feather to see if it connects to my PC. So far, it isn't. I'm running a Windows 10 and I followed this guide:

https://learn.adafruit.com/adafruit-feather-m0-wifi-atwinc1500?view=all

But I get this error:

Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

And the PORT submenu is greyed out.


texts: esp32 crashes when trying to dereference a pointer value

texts:
I have a websocket listener that is giving me a std::string of my message payload (I want the bytes) and I wrote a function that pulls each of the bytes out and puts them into 32 bit integer variables, adds that integer to an array of 32 bit integers, and passes back the pointer address:
uint32_t *get32BitInt(WebsocketsMessage message)
{
  std::string raw = message.rawData();
  uint32_t chunks[message.length() / 4];
  int chunkIndex = 0;
  for (int i = 0; i < message.length(); i += 4)
  {
    uint32_t chunk = 0;
    for (int j = 0; j < 4; j++)
    {
      chunk <<= 8;
      chunk |= raw.at(i + j);
    }
    chunks[chunkIndex] = chunk;
    chunkIndex++;
  }
  return chunks;
}

And I know that parsing and array building works because if I add a loop before I exit the overall function call it prints them out just fine.

And in the function that calls the parser I can print out the address of the pointer that was passed back.
But, as soon as I try to dereference anything my microcontroller crashes:

I know that I'm pretty green to pointers and I'm probably misunderstanding something, but I keep looking at docs and examples of passing arrays as pointers and it seems right.
Also, something worth noting is that it doesn't seem to be an issue with the actual number printing, because if I store the first number of the array into a variable and then try to print a line after the assignment the controller crashes after the assignment but before the next serial print:


texts:
I just got my first arduino starters kit so I'm a total noob in it. My simple LED blinker did work, afterwards I used a switch button with a debouncer script. It worked like I wanted but I wanted to try a buzzer instead of the LED, which did not work. Afterwards when I put the LED back in it didn't work anymore either.

The onboard LED does still work. Does this mean my breadboard had a short circuit? Is there any way I can know this for sure? And what exactly went wrong? Did I have to use a higher resistor?


texts: How to implement multiple LED modes in a sketch with potentiometers?

texts:
My hardware is 4 potentiometers connected to Arduino Analog 0-3, the output is an RGB led driver connected to Digital outputs 9,10,11. The output channels provide access to PWM control of those pins. So idea is the color and intensity can be controlled by the Arduino. I wrote a simple Sketch that reads the potentiometers and then outputs PWM to the RGB driver circuitry. This works great! So the hardware is working! Now comes the last potentiometer...

I want to make the last potentiometer a "mode select" control. It would function like this: If the last potentiometer (Pot4) is turned down all the way, then all lights are off. If the level is turned up a little, the Arduino then controls the RGB channels via Pots 1, 2 & 3. If Pot4 is turned up to just past halfway, the sketch enters a "strobe flash pattern" pulsing all channels on and off. And if the mode control Pot4 is turned up all the way, Arduino turns on all RGB channels.

How do I implement? Mode selection via a potentiometer?


texts: Arduino Due randomly slows down, serial communications stops

texts:
I've got an Arduino Due connected to a Raspberry Pi via Serial3. The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours. Using an oscilloscope, I can see that the Pi keeps transmitting to the Due, but there is no response from the Due. I'm also getting the Due to echo everything it gets from the Pi to Serial, which is connected to my PC. I can see that the Due will stop echoing characters mid way through receiving a message from the Pi.

I then set one of the pins as an output and just keep toggling that regularly. When the Due is waiting for data from the Pi, this signal has a frequency of about 100Hz, i.e. a period of 10ms. I have a counter that goes from 0 to 1000 to control this frequency somewhat. When this error happens and communications stops, I can see that the pulses now have a period of 2.14 seconds, i.e. 214 times slower.

I'm using Arduino-MemoryFree to check for memory leaks but I haven't found any problems yet and I don't seem to be running out of memory. In case it matters, I'm also using the ArduinoJson library. Arduino IDE version is 1.6.7, I've updated the Arduino SAM Boards package to version 1.6.9 (problem was present before the update as well).

Could someone please advise me on what could be causing this slow down?


texts: Help putting an Arduino project on the Internet

texts:
I'm working on quite a big project and I need few advices. Basically, Arduino will be receiving data (Strings) and will work with it. No problems with that, but I don't know what to do with receiving and sending data. Customers (all over the country, so the program will not run on LAN) will send the data, but the question is, via what? Application, that will make a TCP connection to Arduino, send UDP packet or maybe a website? Customers need to have access to data (it needs to be refreshed when arduino deletes it too). What would be the most efficient, easy to use and reliable system?

Next thing I want to know is how to make a connection. Open a port on router and connect arduino to that router? I currently have a python script that actually sends an UDP packet to local IP and it works great, but it is limited to LAN. Will it work if I just change the IP (to external) and send it to the port?

And the last thing (for now). I know how to programm in python and java. Which one is better for connections and GUIs?

Thank you for your help, and if you need any more info about the project, I will be happy to edit this post.


texts: I have solar charge controller and it has a usb port 5V 2A. Can i connect my arduino nano in pin27 in 5V 2A as supply voltage?


texts: Can you output to D+ and D- so that Arduino Uno can be used as a USB device?

texts: My project is basically a set of 5 audio signals (analog) that get altered slightly by Arduino Uno. I convert to MIDI and would then output it to USB, so that it can be used in a program of my choice on the computer. I found a vaguely similar project online with a guide. In that project they write a serial to a MIDI out, and then plug that into a computer. I'm fairly sure I can't just use the TX and run that into the USB, that wouldn't work. So I'm looking for an alternative method.


texts:
I'm making a stopwatch that will measure time between two points.

I want that stopwatch to have a millisecond accuracy.

After the start when someone touch the pad it will show like the time of the touch (15.359) 15 seconds and 359 millis.

I have an arduino uno board.
Everywhere I read it says that millis its not reliable, and in a feel tests it seems not very accurate. Also a lot of places say to use a RTC, but every RTC I found and read about it seem to use only second and not milliseconds. Others say to use a 32 KHz crystal, but I'm not sure if it will fix this. Could anyone give some ideas?

The Arduino will only record time, only that, start and get time and subtract and write on the serial and end.

Thanks!
update 1: thanks Mattia for the edit.

update2 : I was making some  math, and if the device is on for 8 hours, and i want millisecond precision i need something like 30ppb right?
Would this do the job?
http://www.digikey.com/product-detail/en/abracon-llc/AOCJYR-12.800MHZ-M5649LF/535-12624-1-ND/4989030


texts: Arduino IDE Serial Monitor - how to send NUMBERs - not charcters of numbers

texts:
Serial link send and recieves Bytes. Serial monitor at Arduino IDE reads it's input as character.

So if I type '0' in serial monitor, then FW will read byte 48 - I don't want to implement some silly translation from character value to int - I want to input NUMBER as byte into serial monitor - how do I do that?

byte inByte = Serial.read(); // read the incoming byte
if(inByte == 1) // do stuff


texts:
I have an Arduino Mega 2560 where I have used a MicroSD Card Module to Read/Write Data on the Micro SD Card.
I have tried using the Example in the Arduino IDE but the data is not being written or read by Arduino to the SD Card Module. The connections with the module is exactly how it is described in the Sketch.
I have attached pictures of the Connection and the module I use for the same.

The Example sketch for the SD Card Read/Write is also attached.

If there is a problem that you can notice, please let me know what the problem is and if it can be solved.

Thank you in advance.

/*
SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

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

 File myFile;

 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.print("Initializing SD card...");

 if (!SD.begin(4)) {
 Serial.println("initialization failed!");
 return;
  }

  Serial.println("initialization done.");

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

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

    // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
   Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
     while (myFile.available()) {
     Serial.write(myFile.read());
     }
    // close the file:
    myFile.close();
     } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
     }
    }

    void loop() {
   // nothing happens after setup
     }

Connection with Arduino
SD Card Module


texts:
I am creating an application where user input is required. After a user browses through available choices (via buttons and LCD) depending on the choice of the user a function is run from several available.

When the user reboots the Arduino, it starts from the default function, making the user reselect the choice they want..

Is there a way to have persistence of the choice of the user after a reboot?
So that, when a user makes a selection, after a reboot, the arduino will have this selection (=the function that corresponds to this selection) by default.

Maybe if the user input (the buttons) write to an EEPROM or something like this? So that the arduino reads the value from the component?

If such a solution exists, due to limitations i would like to have only one wire for communication with the device.

EDIT: I am using Arduino Due


texts: High power consumption during power down mode

texts:
I try to use power down mode to extend battery life, but no matter what sleep library I use, the power consumption never goes below 3.4-3.6 mA. I'm using a chinese pro mini board with VCC input (but using the RAW results the same).

avr/power sketch:

#include <avr/power.h>
#include <avr/sleep.h>

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

  // Ensure no floating pins
  for(i=0; i<20 ; i++)
  {
    pinMode(i, OUTPUT);
    digitalWrite(i, LOW);
  }

  // Power-down board
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();

  // Disable ADC
  ADCSRA &= ~(1 << ADEN);

  // Power down functions
  PRR = 0xFF;

  // Enter sleep mode
  sleep_mode();
}

void loop()
{
}

rocketscream/Low-Power sketch:

#include <LowPower.h>
void setup() {
}

void loop() {
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
}


texts: I2C from two masters (ATtiny85, ESP8266) to one slave (ATmega328)

texts:
I've been working on a project with I2C protocol where an ATmega328 (Arduino) configured as slave, receives messages from an ATtiny (ATtiny85, ATTinyCore by SpenceKonde) configured as master, or from an ESP8266 (ESP-01, Arduino core) configured as master.

All using the standard wire library, powered with 3.3v (LM1117 regulator), SDA and SCL 4.7kohms pull-ups.
The ESP pins used are RX and TX, with 330ohms pull-ups.

Individually, it works (ATtiny to ATmega; ESP to ATmega), but when i connect the three on the same bus, after the first message it stops working and the ATmega doesn't receive more messages.

Code (modified for readability)

ATmega slave:

#include <Wire.h>

const int ADDRESS = 56;

void receiveEvent() {
    Serial.println(Wire.read());
}

void setup() {
    Serial.begin(9600);
    Wire.begin(MY_ADDRESS);
    Wire.onReceive(receiveEvent);
}

void loop() {
}

ESP master:

#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
const int SDA_PIN = 1;
const int SCL_PIN = 3;

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

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'e';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(2500;)
}

ATtiny master:

#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
// SDA = 0; attiny85 pin 5
// SCL = 2; attiny85 pin 7

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

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'a';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(1000);
}

After some research I found out that the wire library can only work with a single master, is this correct? And the esp can only work in master mode.

Am I doing something wrong, or is this simply not possible?

Are there any protocol alternatives for this design?
A single device that only cares about receiving messages, and multiple other devices that only care about sending messages to the central.

Thank you for your time!


texts:
So I made a program that controls two LED's when two buttons are pressed, but one of the LED's comes on when the button isn't pressed. And what's weird is that if I literally move around the breadboard the LED might turn off for a little, and if hold the button down while doing it the LED remains solid. I have done a lot of taking out and switching wires without any unexpected effects. However, if I switch the LED wires the other LED turns and stays on while the first one turns off, so I am pretty sure that it is a programming error. Here is my code:

const int ledPin1 = 8;
const int buttonPin1 = 1;
const int ledPin2 = 9;
const int buttonPin2 = 2;

int buttonState1 = 0;
int buttonState2 = 0;

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin2, INPUT);
}

void loop()
{
buttonState1 = digitalRead(buttonPin1);
buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == LOW)
  {
    digitalWrite(ledPin1, HIGH);
  }
  else
  {
    digitalWrite(ledPin1, LOW);
  }

  if (buttonState2 == LOW)
  {
    digitalWrite(ledPin2, HIGH);
  }
  else
  {
    digitalWrite(ledPin2, LOW);
  }
}


texts: Can I write to Flash Memory using PROGMEM?

texts:
On the documentation of Arduino, I quote:

  http://playground.arduino.cc/Learning/Memory
  Note: Flash (PROGMEM) memory can only be populated at program burn time. You can’t change > the values in the flash after the program has started running.

And on the PROGMEM description:

  http://arduino.cc/en/Reference/PROGMEM
  Store data in flash (program) memory instead of SRAM. There's a description of the various types of memory available on an Arduino board.

  The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.

So can we or can't we? Or it's not the same thing?


texts:
Hi I am trying to make search GPS (using tinGPSplus) every x time. The problem is when I do compile the code:

void loop()
{
    read=BP_mnger.pressedButton();
    navigateMenus(read);
    dealWithUsedEvents(getmenuUsed());
    setmenuUsed(0);

    if (isStarted && (GPSSearchPeriod<=millis()-oldMillisVallue)) {

        oldMillisVallue=millis();// if i comment this line it works
        Serial.print(F("oldMillisVallue: "));
        Serial.println(oldMillisVallue);
        while (ss.available() > 0){
            if (gps.encode(ss.read()))
                if (gps.location.isUpdated() || gps.date.isUpdated() || gps.time.isUpdated() || gps.altitude.isUpdated() || gps.satellites.isUpdated() || gps.hdop.isUpdated())
                    GPSSentence=makeGPSSentence( );
        }

    }

I get this:

oldMillisVallue: 22355
oldMillisVallue: 24356
oldMillisVallue: 26357
oldMillisVallue: 28358
oldMillisVallue: 30359

When I comment out:

oldMillisVallue=millis();// if i comment this line it works

I get this :

oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
2000,0,0,4294967295,15,43,3,36,5,41,4.066298,48.269157,77,0.12,90,380,98,2,1,3
2000,0,0,4294967295,15,43,3,39,5,43,4.066298,48.269157,79,0.122200,92,380,98,2,1,3
------------------------
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0

oldMillisVallue: 0
oldMillisVallue: 0
2000,0,0,4294967295,15,43,4,39,5,43,4.066265,48.269126,80,0.12,94,380,101,3,2,5
2000,0,0,4294967295,15,43,4,41,5,45,4.066265,48.269127,82,0.121900,94,380,103,3,2,5
------------------------
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0


texts: Connecting a LSM9DS0 9DoF module to Arduino Uno

texts:
I got a bit confused by Sparkfun's hookup guide for this 9DoF breakout module.

It says the VDD-in on the breakout "should [get voltage] regulated between 2.4V and 3.6V", yet in their example they do not hook it up to the Arduino's 3.3V pin, but instead they use the 5V and a bi-directional logic level converter.

Do I need to use the logic level converter, or can I just hook the module up to the 3.3V pin of my Arduino Uno without damaging the breakout module?


texts: How to interface Arduino with NXP PCA8561 LCD segment driver?

texts:
I've just bought few NXP PCA8561AHN LCD segment drivers to do some tests which unfortunately did not went as expected.

I'm familiar with expanders and segment LED displays but LCDs seem to be way more complicated than I thought and there are no libraries or articles to start with.

According to the datasheet, everything is connected correctly, as follows:

VLCD: +3.3V
VDD: +3.3V
VSS: GND
RST: pulled down by a 1K resistor
A0: unconnected
SCL: pulled up by a 1K resistor and connected to A5/SCL on MCU
SDA: pulled up by a 1K resistor and connected to A4/SDA on MCU
PORE: unconnected
SEG0 to SEG13: LCD segments
COM0: LCD pin 1 (backplane #1)
COM1: LCD pin 18 (backplane #2)

PCA8561 draws 35uA when RST is pulled down so it seem to be "active".

Here's how I've tried to initialize the i2C communication with the driver:

#include <Wire.h>

#define address 0x38

const byte numbers[10] = {
  B01000000,
  B01111001,
  B00100100,
  B00110000,
  B00011001,
  B00010010,
  B00000010,
  B01111000,
  B00000000,
  B00010000
 };

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

  Wire.begin();

  Wire.beginTransmission(address);
  Wire.endTransmission();
}

void loop() {

  Wire.beginTransmission(address);

  Wire.write(numbers[5]);

  while (Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }

  Wire.endTransmission();
  delay(250);
}

PCA8561 datasheet

PCA8561 pinout

    .

LCD pinout

Update

void setup() {
  Wire.begin();

  Wire.beginTransmission(address);

  Wire.write(0x00);
  // Wire.write(00000000);
  Wire.write(00101100);
  Wire.write(0x0);

  Wire.write(0x01); // Display_ctrl command (address 01h)
  // Wire.write(00011100);
  Wire.write(010); // frame frequency selection: 96Hz

  Wire.write(0x02); // Display_ctrl_1 command (address 02h)
  // Wire.write(00001100);
  Wire.write(11); // static mode

  Wire.endTransmission();
}

void loop() {
  Wire.beginTransmission(address);

  /*
     Static drive mode
     Using a single backplane, COM0
  */
  Wire.write(0x04); // SEG0 to SEG 7
  Wire.write(B11111111); // all segments ON
  Wire.write(0x05); // SEG8 to SEG15
  Wire.write(B11111111); // all segments ON

  Wire.endTransmission();
}


texts: Can I simulate a clock without an RTC connected?

texts:
I want to program for a timer that works as set timer such as in an oven where user can set their own time. One of the way I know is using an IC(RTC) for the timer. However, I don't have the IC yet only the coding and Arduino.

Is it possible to simulate the Arduino code without having the RTC? Or is there any electrical component that I can use to replace the IC for the time being?
Thank you for your help and comment.I really appreciate that.


texts: how to build rc transmitter and receiver with an old rc transmitter

texts:
I've got an Arduino Mega, an Arduino Nano, two NRF24L01 wireless modules and a old Multiplex Transmitter system.

I want to get the PWM signal and send it to the other arduino which should control the servos and the motor controller.

Is there a good instruction or know somebody how to do that easily?

I need it for a rc plane and the range should be 1km.


texts: Transistor amplifier to drive speaker using Arduino PWM

texts:
I have been working on a project lately which uses Arduino to play a wav file from SD card. I am using TMRPCM library which made the job very easy. But the problem is that the output sound in the speaker is very low. I am using the below single transistor circuit with my Arduino to drive 1.2W / 8ohm speaker

But the Audio output is barely audible. And i have tried many speakers with different wattage but same result.

I am wondering that is there is something wrong with the Wav file i have used for my project. It is 16000Hz/ 8 bit unsigned PCM coded. So in a nutshell my questions are

1) How can i improve the sound obtained from my speaker by making modifications in the transistor amplifier circuit?

2) Was the less audible sound is due to the Wav file i have used?

Kindly help me out, thanks in advance.


texts:
I'm still a beginner at Arduino coding -- I've been researching on how to make functions using void instead of doing goto because reasons...

one thing I've noticed about void is that it has this void loop() {...} parenthesis, what is it for? (and can you provide an example of using it?)

say I make a void function void function1() to call the function I have to use function1(); can I make a function that loops? like the ol' void loop() {...} command we all know and love or do all void functions loop? if not then what happens to a void function after it reaches the end of its function?