texts:
I don't get it. I'm new to Arduino, but not to programming. I don't understand why led pin 13 keeps blinking.

here is my code..

#include <Servo.h>

// X servo angle will stay in [min_x, max_x] range
// Y servo angle will stay in [min_y, max_y] range
// to be adjusted to the size of your living room

float min_x = 5;
float max_x = 50;
float min_y = 5;
float max_y = 35;
int min_freeze = 200;
int max_freeze = 3000;
float minimal_movement = 5;

// finding center of square for starting point
int random_delay;
float x_position = min_x + (max_x - min_x)/2;
float y_position = min_y + (max_y - min_y)/2;
float x_old_position = x_position;
float y_old_position = y_position;
float x_new_position;
float y_new_position;
float x_speed;
float y_speed;
int movement_time;

// Instantiating two servos
Servo x_servo;
Servo y_servo;
int pos = 0;

void setup() {
  y_servo.attach(6);  // attaches the y servo on pin 6 to the servo object
  x_servo.attach(9);  // attaches the x servo on pin 9 to the servo object
  pinMode (13, OUTPUT);
  digitalWrite (13, HIGH);  // switch on  the laser

  //Place the servos in the center at the beginning
  y_servo.write(y_position);
  x_servo.write(x_position);

}

void loop() {
  movement_time = random(10,40);
  random_delay = random(min_freeze, max_freeze);
  x_new_position = random(min_x+minimal_movement, max_x-minimal_movement);
  y_new_position = random(min_y+minimal_movement, max_y-minimal_movement);

  if( (y_new_position > y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
    y_new_position = y_new_position + minimal_movement;
  }  else if ( (y_new_position < y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
    y_new_position = y_new_position - minimal_movement;
  }

  if( (x_new_position > x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
    x_new_position = x_new_position + minimal_movement;
  }  else if ( (x_new_position < x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
    x_new_position = x_new_position - minimal_movement;
  }

  x_speed = (x_new_position - x_old_position)/movement_time;
  y_speed = (y_new_position - y_old_position)/movement_time;
  for (pos = 0; pos < movement_time; pos += 1) {
      x_position = x_position + x_speed;
      y_position = y_position + y_speed;
      x_servo.write(x_position);
      y_servo.write(y_position);
    delay(10);
  }
  x_old_position = x_new_position;
  y_old_position = y_new_position;
  delay(random_delay);

}

Nowhere in this sketch, the line "digitalWrite (13, LOW);" is contained, yet I am unable to keep the LED on solid without blinking when the Arduino is looping. I've other people do it, with this code, I don't get what I'm missing!

Windows 7 64bit, Arduino Uno board, Arduino 1.8.9 program


texts: Configure Arduino IDE to not quit when the last sketch is closed

texts:
The Arduino app takes a long time to launch on MacOS. (The Initializing Packages... stage takes over a minute.) It's very frustrating when you accidentally close the last sketch window and the app quits. Then you have to wait for it launch again.

Is there anything that can be done to stop it from closing automatically?


texts: ESP8266 Arduino MQTT callback with dynamic topics

texts:
I have a program that depending on user input, it creates one or several objects that will publish data to a MQTT broker, each one with a different topic. This is already done. The ESP8266 also has subscribe itself to the same topics it publishes.
Now, the problem is that I have to create a dynamic callback in the ESP8266 to read the all the posible arriving topics to which the ESP8266 has subscribed and I am having trouble with that.

The callback function model is:

void MQTTcallback(char* topic, byte* payload, unsigned int length) {

// handle message arrived

}

The possible topics can be:

ObjectTL/TL_1

ObjectTL/TL_2

ObjectTL/TL_3

...

ObjectTL/TL_X

The number (TL_X) depends of the user input I mention at the beginning.
Thanks!


texts:
I'm currently studying embedded systems on eDx.
https://courses.edx.org/courses/UTAustinX/UT.6.01x/1T2014/info (must login to see)
http://users.ece.utexas.edu/~valvano/edX/index.html (don't need to login)
and I found out that TM4C123 is quite similar to Arduino.
but I haven't worked TM4C123 yet.(I ordered it and I'm waiting for it)
 I don't know much about it.
and it's not that popular as Arduino I guess.
so If anyone has used Tm4C123, please give me some information compared to Arduino.


texts:
Wanna get your advice regarding powering up Arduino Uno using AC/DC Adapter to the barrel jack.
The first adapter I use couldn't work and the shop which I bought it from said the adapter was short circuit-ed.
Out of goodwill, she replace it for free and I tested it out again. The first few tries it worked perfectly fine but stopped working (suspected short-circuited again).
The adapter output is DV9V - 2A.
The circuit consists of 2 ultrasonic sensor and 1 buzzer.
I am quite sure the Arduino circuit does not draw more than 2A of current.
Any idea what's the issue? Thanks!
EDIT -
I've uploaded a photo of the schematic done using Tinkercad. I am using a different breadboard thus the configuration as shown.


texts: How can I connect an Arduino / ESP8266 to an Azure MySQL database?

texts:
I am currently trying to connect an ESP8266 to my Azure MySQL database via WiFi, but have not yet been successful.

I have tried a bunch of guides, but no luck and I'm running out of ideas. I have made a connection to an IoT Hub in Azure but could not forward the messages to the MySQL database in the cloud. I managed to get it stored in a blob datatype but had so many issues with it that I kinda scratched that idea.

Last thing I tried was trying to implement the example from
https://github.com/ChuckBell/MySQL_Connector_Arduino
more specifically the 'connect_wifi' example. I was unable to find the ip of my azure server so i tried using some of the code from the 'connect_by_hostname' but no luck there.

I'm new to Arduino and cloud in general so any help is appreciated.


texts: Can I use NodeMCU with Arduino to connect to wifi or do I need a separate module?

texts: I am just starting out with electronics. I got a Arduino Mega 2560 board and am able to do simple things like blink. Now I want to start a project on IoT and want to connect this board with internet. I got some leads here. While googling ESP8266, I came across NodeMCU which has a processor too. I already have Arduino, so can I use only the wifi module of NodeMCU and connect it to Arduino?


texts: Read information from Twitch's API and execute actions depending on the output

texts:
i'm trying to create a display that notifies me when someone goes live on twitch. I need to acess the API and check if the 'stream' object is null or not. Then, perform an action depending on this.

The address to the API is http://api.twitch.tv/kraken/streams/pedrinholuizf

What can I do? I'm using an Arduino Leonardo with the Ethernet Shield.


texts:
After trying for a good month.. looking like a Newbie I have not managed to log the result of barcode scanner , using rtc SD module and a waveshare scanner connected via UART to ports 2 and 3 from the arduino.
Main idea was being able to log into the SD card under the header Barcode and time, the barcode scanned and time of scan.
I know how to create files with current date + int. CSV , consecutively if one was already created, deleted them...etc
However as by not reaching the desired result I reduced and further reduce the code so at the end I am happy that the barcode I scan is logged into the SD card.
It follows mess--code..not messy enough I have some more ...honestly..anyway
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <Wire.h>
#include "RTClib.h"
#define rxPin 2
#define txPin 3
SoftwareSerial mySerial = SoftwareSerial (rxPin, txPin);

RTC_DS1307 RTC;
File myFile; // file to be created and where data is to be to stored

char c = ' ';         // stores the latest character from the serial input  buffer
int length = 30;      // Max. lenght of te buffer
char buffer [31];     // Char Array to store theincoming data
char termChar = 10;   // terminating character
byte index = 0;       // index position of the bufffer, so where the next character t come shall be copied to
boolean haveNewData = false; // Flag to tell the sketch we have data
const int chipSelect = 10; //CS pin For SD card.

void setup()  {

  Serial.begin(9600);

  mySerial.begin(9600);

  Wire.begin();

  if (!RTC.begin()) {
    return;
  }

  pinMode(10, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    return;
  }
  myFile = SD.open("test.CSV", FILE_WRITE);
  if (myFile) {
    Serial.print("Writing to file...");
    myFile.println("Hello BarWorld");
    myFile.close();
  }
}

// right now I scann a barcode

void loop()
{
  readmySerial();
  if ( haveNewData ) {  processNewData();  }
}

void readmySerial()
{
     if (mySerial.available())
    {
      c = mySerial.read();
      if (c != termChar)
      {
        buffer[index] = c;
        index = index + 1;
      }
      else
      {
        buffer[index] = '\0';
        index = 0;
        haveNewData = true;
      }
  }
}

void processNewData()
{
  myFile = SD.open("test.CSV", FILE_WRITE);
  if (myFile) {
  myFile.println(buffer);
  myFile.close();}
  }


texts: Powering Motor shield and Arduino Mega Separately

texts:
I'm trying to build a fire fighting robot, that uses 2 BO DC motors, 2 Servos - MG996R and SG90. For them I'm using Motor Shield v1 of Adafruit's make that uses 2 L293D IC's and a 74HC595 shift registers.

Now, I'm placing the motor shield over Arduino Mega and trying to connect other components such as Flame Sensor, Ultrasonic Sensor and submersible DC Water Pump.
As soon as I try to power up ultrasonic sensor, the power indicating LED's on both the shield and Mega goes off.

I've been testing this with simple USB connected power supply and to my understanding the power being supplied is insufficient.
Since it would be a moving cart, I would like to know whether there is any way to power up Shield and Mega separately by a 9v Battery?


texts: How many clients can connect to an ESP32?

texts:
I am using an ESP32 as my master and 10 ESP8266-07s are connected to the master that is in AP mode.

But I need at least 12 clients.
Please help me to increase the number of clients the ESP32 can handle in AP mode.

I have read this article but it did not help me
ESP32 AP max connections: 4 or 10?


texts: What is the lowest resistance pot that is useful with an analog input?

texts:
Background

I've dabbled in electronics since my parents gave me a 150-in-1 kit in the 1970's but never had formal training. My dad repaired Honeywell mainframes so taught me to solder when I was 8. I have a decent set of equipment like irons, parts, meters, etc. and realize I know enough to be dangerous, which is why I avoid mains-powered stuff.  I'm not a newbie but am all too aware of the many holes in my knowledge.  I'm doing this for fun and in a way that allows for failures to be expected, cheap, and educational.

Project

I have a WS2812b LED strip connected to an Arduino Uno and am using various animation libraries to drive it. The goal is to move to a pro mini once the hardware is more settled and use it for creative lighting inside my house or garage.  I started with just the strip and let it display different animations in a sequence based on time but then wanted to attach a button which would advance to the next animation.  After implementing debouncing it worked fine and I moved on to adding a potentiometer to select the speed of the current animation; increasing or decreasing the delay between each 'frame'.  Of interest here is I was using old pots (panel mount not for typical board use - hence I had to solder wires to them just to use them in any configuration) and not doing any ohms law calculations, just hooking up the hardware and tuning the values for mapping the detected voltage to the desired delay by checking printed output from the serial monitor.

I'm happy with the general setup when using a breadboard but when I went to solder something more permanent on perfboard I ran into a problem; the speed control wouldn't work.  I'm sure the first pot I used was 10k but when I checked it with the meter it registered as completely open so I figured I had blown it. Thinking that I needed to control the current I read posts like this one and this one about limiting current I felt better and proceeded to replace the pot with a 25 ohm version thinking that the only difference would be in calibrating the values for mapping the detected voltage to the desired delay.  The behavior I got was randomly fluctuating values for the delay and when I hooked up the prototype using USB to my laptop I could see that the analogread() values were fluctuating wildly within a range even when I wasn't manipulating the pot yet nothing I did could get it to be consistent.  My first thought was that there was a problem with ground so I rechecked the connections but they all tested fine, including still reading 25 ohms along the outside terminals and varying values on the wiper consistent with rotating it along its path from end to end.  When I gave up on my protoboard and returned the circuit back to the breadboard I replaced the full size pot with a 10k small one meant for breadboards and the speed control works again.  This leads to my question.

Question

Is there a minimum value for a potentiometer connected to an analog input of an arduino, or is it more likely that there was an issue with my soldering job on the protoboard?  I don't have a picture of the board because I've already desoldered components from it but I can tell you that it was my first attempt at perfboard soldering and it would not win any prizes, sort of the 'face only a mother could love' sort of thing. If it matters, I was using analog input A2.


texts: How to make 1 second delay more accurate?

texts:
I have written two (1 second) delay programs.

The first program as follows:

void setup()
{
Serial.begin(9600);
TCCR1A = 0;
TCCR1B |= (1<<CS12);
TCCR1B &= ~(1<<CS11);
TCCR1B &= ~(1<<CS10);
TCNT1 = 3036;
TIMSK1 |= (1<<TOIE1);
}

ISR(TIMER1_OVF_vect)
{
  Serial.println(millis());
  TCNT1 = 3036;
}
void loop()
{
}

Whose output is as follows:

999  // 1 sec
1999 // 2 sec
3000
3999
5000
6000
7001
8000
9000
10001
.
.
.
58012
59013
60013
61012
62013 //60 sec

It has an error of around 13 ms at 1 minute and at 1 hour it will be 780 ms and in one day it will be around 19 seconds.

The second program is as follows:

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

void loop() {
  Serial.println(millis());
  delay(1000);
}

Whose output is near about as same as the first one's.

Is there any way to decrease the error and make it more precise? So that I can use it in my Arduino based stopwatch?


texts: How can I connect a force sensitive resistor to a vibration motor via Arduino?

texts:
Please forgive me if my knowledge is limited--still very new to this!

I'm currently working on my senior thesis for my Industrial Design program and I'm struggling to figure out the components and code I need to link a FSR and a vibration motor. Basically the idea would be that high pressure on the FSR would equate to high vibration on the motor and vice versa so you could get variable intensity based off of how hard you squeeze the sensor. I've looked up a lot of different circuit diagrams for using a vibration motor with an Arduino and many of them seem to indicate that I will need a 1N4001 Diode, a 2N2222 NPN Transistor, a 1KΩ Resistor, and a 0.1µF ceramic capacitor. I'm currently using the Arduino UNO R3 and I don't want to fry it so before I go tinkering too much I wanted to ask what you all might do to achieve what I'm aiming to do.

Thank you and I appreciate any and all feedback!


texts: How to call URL with Arduino Ethernet shield?

texts:
I'm working on Arduino and Ethernet shield.

I need to call a URL. How can do it? (This URL is HTTP API to send an SMS to my phone).

url:
http://api.clickatell.com/http/sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello


texts: How to make two WIR 1186 RF transceivers communicate over serial communication?

texts:
I want to have two RF transceivers communicate, one as transmitter and one as a receiver, for longer distances. For that I'm using WIR 1186 RF modules with Arduino.

Pin connections are as below:

Arduino :5v,gnd,RX,TX,2,3
WIR1186 :VCC,gnd,Tx,Rx,prg,cts

But Arduino is not serially communicating with the WIR1186 module.

Below is the code:

char ch;
int prog = 2;
int cts = 3;
int stat;
unsigned int output;

void setup() {
  Serial.begin(9600);
  pinMode(prog, OUTPUT);
  digitalWrite(prog, LOW);
  stat = digitalRead(prog);
  Serial.println(stat);
  Serial.write("B=9600\r\n");
  output = Serial.read();
  Serial.println(output);
  digitalWrite(cts, HIGH);
}

void loop() {
  Serial.write('a');
  delay(1000);
}

Here is the datasheet of WIR1186

Please help me out with this.


texts: Arduino Editor: Monitor menu show "Serial port unavailable"

texts:
Ubuntu 16.04LTS 64bit, Arduino Pro Mini board (ATmega 328P, 3.3V 8Mhz)
I have problem with WEB editor: I selected Arduino Pro mini and ticked "8Mhz ATmega 328P". I tried to upload "blink" test program from Examples, but Web editor show "Error uploading, check if selected board is currently available." And Monitor menu show "Serial port unavalable".

$ dmesg | grep tty
[    0.000000] console [tty0] enabled

I tried to reboot, not help. The green LED on Arduiono is "on" and red LED is blinking. I tried to verify the built-in COM port, in terminal run command    dmesg | grep FTDI, but no any output returned.

$ ls -l /dev/ttyUSB*
ls: cannot access '/dev/ttyUSB*': No such file or directory

It looks that FTDI USB to Serial port converter not recognized on Ubuntu?


texts: Serial Commmunication between two arduino

texts:
I want to send the voltage magnitude received on an analog pin of atmega328Pu to another arduino uno using Serial communication pins TX and RX and display the value on the receiver arduino's Serial monitor.

Transmitter Arduino Code:

void setup()
{

  Serial.begin(9600);

  pinMode(A0, INPUT);

}

void loop()

{

  int voltage=analogRead(A0);

  Serial.println(voltage);

}

Receiver Arduino Code:

void setup()

{

  Serial.begin(9600);

}
int incomingByte = 0;

void loop()
{
if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
}

}

Problem: Now the Problem I am facing is that Serial Monitor of Receiver arduino does not shows anything, it remains blank. Please analyse this system help me in finding out the best way to get around this problem?


texts: Advice needed, commercializing an Arduino Due project

texts:
We have a project using an Arduino Due, and we are looking to commercialize the project. How would one typically proceed? Would you use the Arduino Due inside the project? This seems very amateur.
Using another Arduino is not an option due to the number of interrupts, number of pins, and processing power required.
Thanks!


texts: upload.tool not used in custom boards.txt?

texts:
I've created a custom board in boards.txt and changed the upload.tool to a nonsense value, and yet when I do an upload the IDE still calls avrdude.

For example, In boards.txt I've changed the line...

tile.upload.tool=avrdude

...to...

tile.upload.tool=nogood

...and added these lines to platform.txt...

# NOGOOD programmer

tools.nogood.cmd="dir"
tools.nogood.program.pattern="dir"
tools.nogood.upload.pattern="dir"

...and reloaded the IDE and hit upload.. and it still runs AVRDUDE.

(Note that my board ID is tile)

I've verified that I am editing the correct boards.txt by changing the cores key to nogood and this does generate an error.

Is boardid.upload.tool not the right place to change the recipe called when upload is hit?

How/where does the boardid.upload.tool=toolname key in boards.txt get mapped to the tools.toolname.upload.pattern key in platforms.txt?

I am using Arduino IDE version 1.8.3.

The custom boards.txt is in the directory Arduino\hardware\Move38\avr.

This full custom platform package is here...

https://github.com/bigjosh/Move38-Arduino-Platform

Thanks!


texts:
My project has 4 float switches, 2 valves and 3 pumps. I created a sketch and uploaded it. But my project keep all "OUTPUT" at "HIGH" all the time. I couldn't find what the problem, can you help?

This is my sketch:

#include <DS3231.h>
#include <Wire.h>
#include <LiquidCrystal.h>
DS3231  rtc(SDA, SCL);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int x = 45;
int y = 47;
int z = 41;
int w = 43;

int WaterIn =  40;
int WaterOut = 42;

int Pump1 = 25;
int Pump2 = 24;
int Pump3 = 27;

void setup()
{
  rtc.begin();
  lcd.begin(16,2);
  // Start the I2C interface
  Wire.begin();
  // Start the serial interface
  Serial.begin(9600);
  //rtc.setDOW(TUESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(1, 15, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(6, 6, 2017);   // Month, Day, Year

 //Setup FLoat Switch Pins
  pinMode (x, INPUT);
  pinMode (y, INPUT);
  pinMode (z, INPUT);
  pinMode (w, INPUT);

 //Setup Irrigation Valves
  pinMode(WaterIn, OUTPUT);  //irrigation "in" valve
  pinMode(WaterOut, OUTPUT);  //irrigation "out" valve

//Setup Pumps
  pinMode(Pump1, OUTPUT);
  pinMode(Pump2, OUTPUT);
  pinMode(Pump3, OUTPUT);
}  // end of setup

void Calendar(){

 lcd.setCursor(0,0);
 lcd.print("Real Time Clock  ");
 lcd.setCursor(0,1);
 lcd.print("Time: ");
 lcd.print(rtc.getTimeStr());
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Date: ");
 lcd.print(rtc.getDateStr());
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Day: ");
 lcd.print(rtc.getDOWStr());
 lcd.print("           ");
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Temp: ");

 lcd.print(rtc.getTemp());
 lcd.print(" C");
 lcd.print("          ");
 delay(1000);
}  // end of setup

void Valves(){
    int pinToTurnHigh = 24;
    if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))  //Condition 1
    {
        pinToTurnHigh = WaterIn;
        pinToTurnHigh = Pump1;
        pinToTurnHigh = Pump2;
        pinToTurnHigh = Pump3;
    }
    if ((x == LOW) && (y == LOW) && (z == HIGH) && (w == HIGH))  //Condition 2
    {
       pinToTurnHigh = WaterOut;
    }
    resetAllPumpValve();
    digitalWrite(pinToTurnHigh, HIGH);
}  // end of setup

void resetAllPumpValve(){
     digitalWrite(WaterIn, LOW);
     digitalWrite(Pump1, LOW);
     digitalWrite(Pump2, LOW);
     digitalWrite(Pump3, LOW);
     digitalWrite(WaterOut, LOW);
}  // end of setup
void loop()
{
    Calendar();
    Valves();
    resetAllPumpValve();
}  // end of loop


texts: How to store the content of message sent to GSM module (SIM900a) into a string?

texts:
I am Working on a project to control the system via the GSM messaging Scheme.

eg:- If I send 1 via an SMS to the GSM module, the Arduino would read this message and disable or enable the system.

But I am unable to process the message, since the received message format is;

  +CMT: "+91xxxxxxxxx","","17/07/07,21:57:04+08"

#include<SoftwareSerial.h>
SoftwareSerial myGSM(9,10);// Rx and Tx
int a;
int b[5];
int actuator = 5;

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

void loop()
{
  msg_read();
  for( int i = 0; i < 5;  ++i )
   b[i] = (char)0;
}

void msg_read()
{
  myGSM.println("AT+CNMI=2,2,0,0,0");//AT command to recieve live SMS
  delay(1000);
  if (myGSM.available()>0)
  {
    char c;
    char store[30];
    c = myGSM.read();
    store[30] = c;
    int a = 10;
    a += 1;
    store[a] = 0;
    char* command = strtok(c, ",");
    while ( command != 0)
    {
      int i = 0;
      b[i] = atoi(command);
      command = strtok(0, ",");
      i++;
    }
  }
  for( int j = 0;j <= 2; j++)
  {
  msg_send(b[j]);
  }
}

void msg_send(int c[])
{
   myGSM.println("AT+CMGF=1");//Sets GSM module in text mode
  delay(1000);
  myGSM.println("AT+CMGS=\"+91xxxxxxxxxx\"\r");
  delay(1000);
  if( c[0] == 1)
  {
    digitalWrite( actuator, HIGH);
    myGSM.println("SYSTEM ENABLED");
  }
  else if( c[0] == 2)
  {
    digitalWrite(actuator, LOW);
    myGSM.println("SYSTEM ENABLED");
  }
  if( c[1] == 3)
  {
    myGSM.println("GEOFENCE ENABLED");
  }
  else if( c[1] == 4)
  {
    myGSM.println("GEOFENCE DISABLED");
  }
}

Requirement

I need a code that will allow me to recover the message content and compare it with a predefined string.
Can I use the GSM library with SIM900a module or is it reserved only for GSM shield?

I am using an Arduino Uno.


texts: Servo only going one direction till it reach limit

texts:
I have a ATTiny85 with a standard servo motor attached to it. I would expect the following sketch to make the servo to oscillate between position 60 and 100 but instead it just to to it's limit (180) and grinds there...

Any ideas ?

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

Adafruit_SoftServo servo;

#define MOTOR_PIN 0

bool flip = true;

void setup() {
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  // Set up the interrupt that will refresh the servo for us automagically
  OCR0A = 0xAF;            // any number is OK
  TIMSK |= _BV(OCIE0A);    // Turn on the compare interrupt (below!)

  servo.attach(MOTOR_PIN);
  servo.write(90);           // Tell servo to go to position per quirk
  delay(15);
}

void loop() {
  if(flip) {
    servo.write(60);
    delay(150);
    !flip;
  }
  else {
    servo.write(100);
    delay(150);
    !flip;
  }

  delay(500);

}

// We'll take advantage of the built in millis() timer that goes off
// to keep track of time, and refresh the servo every 20 milliseconds
volatile uint8_t counter = 0;
SIGNAL(TIMER0_COMPA_vect) {
  // this gets called every 2 milliseconds
  counter += 2;
  // every 20 milliseconds, refresh the servos!
  if (counter >= 20) {
    counter = 0;
    servo.refresh();
  }
}

Thanks.


texts: I have been using only Arduino Uno. Now I am about to buy Mega. But a question rises. Are those 4 Serial Ports of Mega controlled still through one usb cable?


texts: Draw polygon on LCD from GPS latitude and longitude

texts:
I'm working on a personal project  (a usefully tool based on ublox GPS and Arduino Mega that can measure distance between 2 points, compute area, speed, save data on SD card)

Now I want to add new feature and when I show the area(in m^2) on LCD, I want to show the polygon built by more coordinates.

I tried all I know, I searched for solutions but without success.

How can I "scale down" coordinates to make them fit in a x,y system with max size (320*480, LCD size) ?


texts:
so I have a wifi shield and I am sending a web request, but its not going through. I know it's not the server because the other function of the program works properly. My code is available on pastebin

EDIT:

The request that is not working is on line 318


texts: Compiling mbed.h in Arduino IDE using Arduino Nano 33 BLE

texts:
I found out that is not possible to compile my new Arduino Nano 33 BLE including the mbed.h library. I can only compile it if I use the deprecated version of the board with version 1.1.4. If I switch to the newest one, the 2.0.0, the compiler does not work.
Do you know if there are some security reason for it?
EDIT:
WARNING: library MaximWire-1.0.2 claims to run on nordicnrf52, mbed architecture(s) and may be incompatible with your current board which runs on mbed_nano architecture(s).
undefined reference to `digitalPinToPinName(unsigned char)'collect2.exe: error: ld returned 1 exit status


texts:
I'm trying to make two functions one will be running in a loop the second one will be running with a time interval of 1 seconde
I made a piece of code to do so it runs fine in the beginning but after a bit of time (aproximately 35 secondes) the code loses its mind and starts executing without caring about the delays.
I don't know what's going on
here is my code

void loop() {
  if(millis()-prev>=gap){
    Serial.print("Prev: ");Serial.println(millis()-prev);
    prev = millis();
  }

  Serial.print("Prev2: ");Serial.println(millis()-prev2);
  delay(mils);
  prev2 = millis();
}

You can try it yourself the code runs fine at the begining but bugs after some time.
What i'm trying to acomplish is having some code that runs in a loop and a function that will run each seconde.
the code is tried on multiple boards of Arduino Uno.


texts: How to Capture Data from a Webpage in Arduino and Display it over Serial Monitor of ESP8266?

texts:
My Code is as follows->

#include <SoftwareSerial.h>

SoftwareSerial ESP8266(8,9);

String inData;
void setup() {
ESP8266.println("AT");
delay(1000);
ESP8266.println("AT+RST");

}

void loop() {
 String cmd = "AT+CIPSTART=\"TCP\",\"";
 cmd += "api.thingspeak.com";  // 184.106.153.149 thingspeak IP address
 cmd += "\",80";
 ESP8266.println(cmd);

 if(ESP8266.find("Error"))
 {
   Serial.println("AT+CIPSTART error");
   return;
}
String hostt = "GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA";
hostt += "\r\n";
hostt += "Host:api.thingspeak.com";
hostt += "\r\n\r\n\r\n\r\n\r\n\r\n";
ESP8266.println(hostt);

cmd = "AT+CIPSEND=";
cmd += String(hostt.length());
ESP8266.println(cmd);

if(ESP8266.find(">")){
ESP8266.print(hostt);
}
else{
ESP8266.println("AT+CIPCLOSE");
// alert user
Serial.println("AT+CIPCLOSE");
}
delay(5000);
}

Is this the write code? Where am I going wrong?
I am not able to see the required fetched data.
Help me with this.


texts:
I am working on a project were I am putting my board into deep sleep mode, and it wakes up with an interrupt from a sensor.  When it wakes from deep sleep I would like to send a message to my MQTT broker.  The wiring works, the interrupt works, however, the code does not.

When I use the posted code, everything looks fine in the console, I get all my print statements which would make me assume it is working.  However, my MQTT broker does not show any messages.  But, if I move "sendMQTTMessage()" to the loop function it works fine and the messages come through to my broker.

Any suggestions would be greatly appreciated

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

const char* ssid = "*";
const char* ss_pswd = "*";
const char* mqtt_server = "*";
WiFiClient EspClient;
PubSubClient client(EspClient);

void wifi_setup() {
  Serial.print("Connecting to: ");
  Serial.println(ssid);
  WiFi.begin(ssid, ss_pswd);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String ClientId = "ESP8266";
    ClientId += String(random(0xffff), HEX);
    if (client.connect(ClientId.c_str())) {
      Serial.println("connected");
      client.publish("outtopic", "hello world, finally");
      client.subscribe("/room/test");
    } else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println("Try again...");
      delay(5000);
    }
  }
}
void sendMQTTMessage() {
  Serial.println("sending your message");
  if (!client.connected()) {
    reconnect();
  }
  client.publish("belmont/sensor/pir/hallway", "on");
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: ");
  Serial.println(topic);
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
}
void setup() {
  Serial.begin(115200);
  wifi_setup();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  sendMQTTMessage();
  Serial.println("going into deep sleep");
  ESP.deepSleep(10 * 1000000);
}

void loop() {
//  sendMQTTMessage();
//  delay(5000);
}


texts: Arduino sizeof Servo array objects is.. wrong?

texts:
After searching for a quite long while over the internet, I have no choice but to try asking someone if they can explain me this apparently strange situation.

I'm doing some tests using some servo motors, trying to move them almost together using millis() and Servo object.

It is, of course, working either for single Servos and multiple servos.

The case, more detailed, is about this:

Move one, two or more servo motors together.
Force them to take ALMOST the same time to accomplish any action.
Have a dynamic number of servos.

About the first two points I had no problems to solve them, I was easily able to make a function and then make a library to accomplish such a job.

However, since I'm NOT that used to C++ and I was wondering if it actually was possible to create an array of Servo objects, like you can actually do, on arduino, with strings:

String stringArray[] = {"string1", "string2", "and so on, I love it."};

So, after wondering a while, I've tried this:

Servo servObject;
Servo servObject_2;
Servo servObject_3;

Servo servos[] = {servObject, servObject_2, servObject_3};

And you know what's cool? my function is actually working correctly by forcing the amount of elements of the servos array.

What I mean by that is that if I force my function to know that it is going to have 3 elements into the array it will, of course, work; However, for some reason, if I use sizeof(servos); the value returned, surprisingly, is 2....
Moreover, if I only push two servo objects instead of three into the servo array, its sizeof returns 6.

By googling, I've found out a couple of discussions about the fact that, for some reasons, in some cases, sizeof returns an incorrect value (if I'm not wrong it was the correct value -1), but in my case it apparently is not following any logic at all.

The board I'm using is an Arduino nano w/ ATMEGA 328.

Any idea of why it is not returning the correct value? Am I actually going totally wrong because I shouldn't make an array of servo objects?

ps: I didn't post the whole code because it would've been useless, since the sizeof is the first function called in the loop()

Regards,

briosheje


texts: ESP-NOW: Master and Slave at the same time

texts:
I am interested to use ESP-NOW as a means to transmit data between two ESP32's back and forth, - each ESP receives and sends data, taking turns. The example library provides an example sketch for Slave and one for Master, which allows for one-directional data flow. However, I would like to use ESP-NOW for two-way communication. Is it possible to combine both of these sketches to allow the data to flow in both directions at the same time?

I'm assuming two ESP's won't be able to send data at the same exact time, so the best approach to start, I think, would be to wait until a packet has been received before sending one from the other end. Here's a snippet of code which I tried to use, but failed:

void setup()
{
  Serial.begin(115200);
  WiFi.mode(WIFI_MODE_APSTA);
  // configure device AP mode
  configDeviceAP();
  // This is the mac address of the Slave in AP Mode
  Serial.print("AP MAC: ");
  Serial.println(WiFi.softAPmacAddress());
  Serial.print("STA MAC: ");
  Serial.println(WiFi.macAddress());
  // Init ESPNow with a fallback logic
  InitESPNow();
  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info.
  esp_now_register_recv_cb(OnDataRecv);
  esp_now_register_send_cb(OnDataSent);
}

unsigned long nextManage;

void loop()
{
  // In the loop we scan for slave
  ScanForSlave();
  // If Slave is found, it would be populate in `slave` variable
  // We will check if `slave` is defined and then we proceed further
  if (slave.channel == CHANNEL2)
  { // check if slave channel is defined
    // `slave` is defined
    // Add slave as peer if it has not been added already
    bool isPaired = manageSlave();
    nextManage = millis() + 10000;
    while (isPaired)
    {
      if (packetRecieved)
      {
        packetRecieved = false;
        // Send data to device
        sendData();
      }

      unsigned long t = millis();
      if (t > nextManage)
      {
        nextManage = t + 10000;
        // pair success or already paired
        isPaired = manageSlave();
      }
    }
    Serial.println("Slave pair failed!");
  }
}


texts: Concatenate two non constant char arrays in Arduino

texts:
I have two non constant char arrays. One is "buff" and other is "buffa". I get values in buffa via rf transmitter of other Arduino and I want to append those data to the data inside of buff. Then I will send all data to other Arduino. So I don't want to send two different char arrays. I want to send them all at once as just one array.

I TRIED SPRINTF BUT IT DOESNT WORK.

char buffa[144];
    char buff[1000];

void loop() {

  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  sprintf(buff,"<status>\n");

    if (vw_get_message(buf, &buflen)) { // check to see if anything has been received
      int i;
      for (i = 0; i < buflen; i++) {
        buffa[i] = (char) buf[i];  // the received data is stored in buffer

      }
    }

  distance1 = getDistance(initPin1, echoPin1);
  sendData(3, distance1);

  sprintf(buff, "%s", buffa);

delay(5000);
 const char *msg0 = buff;

 vw_send((uint8_t *)msg0, strlen(msg0)); // Send control character
 vw_wait_tx();

 Serial.print(msg0);

}


texts: What are the steps involved in porting an Arduino library?

texts:
I want to use the Adafruit CC3000 and its Arduino libraries on another platform. In this case it's the Arduino pin compatible PSOC4 Pioneer Kit. This is an ARM Cortex M0 based platform.

My question is: How would I go about porting a library like this? What are the steps, key files etc?

One obvious issue is that PSOC Creator does not readily support C++.

One positive might be that the Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU.

NOTE: If you think this question is off topic; please head over to this question on Arduino Meta to voice your opinion on whether questions on Arduino Compatible devices are appropriate for this list.


texts: Make upload stuck on osx 10.10 bare-arduino-project

texts:
I followed the instructions in here, including to use arduino IDE v 1.0.5, but when I tried to make upload it stuck. I can upload it when using Arduino IDE.

Here is what I got:

  mkdir -p /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject
 /Applications/Xcode.app/Contents/Developer/usr/bin/make reset
 /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/Arduino-Makefile/bin/ard-reset-arduino  /dev/cu.usbmodem1421
 /Applications/Xcode.app/Contents/Developer/usr/bin/make do_upload
 /usr/local/bin/avrdude -q -V -D -p atmega328p -c arduino -b 57600 -P /dev/cu.usbmodem1421 \
        -U flash:w:/Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject/mySecondProject.hex:i

What did I miss?

I use: Bare-Arduino-Project, OSX 10.10, XCode 6.1, Arduino Uno, my Makefile


texts: DCMotorTest from the Adafruit site – got fatal error exit status 1

texts:
New to Arduino, I plugged in DCMotorTest from the Adafruit site and got this error message: a fatal error exit status 1

/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}

My error message was:

Arduino: 1.6.7 (Mac OS X), Board: "Arduino/Genuino Uno"

/Users/student/Downloads/Adafruit_Motor_Shield_V2_Library-master/examples/DCMotorTest/DCMotorTest.ino:11:34:
 fatal error: Adafruit_MotorShield.h: No such file or directory
 #include <Adafruit_MotorShield.h>
                                  ^
compilation terminated.
exit status 1
Error compiling.

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


texts: Checking what ESP8266 module that is in use

texts:
I have this script where I have connected an ESP-01 to an SSD1306 OLED screen. However, the script I'm using needs adaption for ESP-01 as this module requires the I2C pins to be defined.
So basically I need to add a line that says Wire.begin(2, 0); so make the screen work with the ESP-01.
Whoever, I would love to have a check that is wrapped in a #ifdef so the code will work out of the box with multiple ESP modules without changing the source code.
Is there some way I can check if the module in use is an ESP-01?


texts: Why this code for ESP8266 goes into STA+AP mode?

texts:
I'm using Arduino IDE 1.6 nightly with Generic ESP8266 Board.

Why this code runs in mesh mode instead of simply connecting to my wifi?
My goal is to test out MDNS, but so far I found this:

board connects to my wifi
but board also opens an ESP- access point
when connected to my wifi on my computer I cannot resolve http://esp8266-webupdate.local/update
when connected to the open ESP- wifi I can resolve http://esp8266-webupdate.local/update

To my understanding such code should just connect to my wifi and I would then be able to navigate to http://esp8266-webupdate.local/update, am I missing something?

output (note STA+AP)

Booting Sketch...
......
Connected, IP address: 192.168.1.20
Mode: STA+AP
PHY mode: N
Channel: 10
AP id: 0
Status: 5
Auto connect: 1

code

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

const char* host = "esp8266-webupdate";
const char* ssid = "myhomeap";
const char* password = "blabla";

ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

void setup(void){

  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting Sketch...");
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  WiFi.printDiag(Serial);
  MDNS.begin(host);

  httpUpdater.setup(&httpServer);
  httpServer.begin();

  MDNS.addService("http", "tcp", 80);
  Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
}

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


texts: Wake up arduino mini with a external signal from a rf wake up receiver

texts:
I am working in an arduino which sleeps after 1.2 seconds of running time and wake up when receiving a signal in the pin 2, but this last part is not working. I tried with the four modes of the interrupt ( LOW, CHANGE, RISING, FALLING) and also tring to connect it to vcc and disconect it myself, depending on the mode.

The sleeping part works as wanted

#include <avr/sleep.h>

// ### pin paging ### \\

#define RLEDPIN 13       //pin for red led
#define GLEDPIN 12       //pin for green led
#define BLEDPIN 11       //pin for blue led
#define wakePin 2        // pin used for waking up

// ### measure variables ### \\
unsigned long times;

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

void setup()
{
  Serial.begin(115200);
  pinMode(RLEDPIN, OUTPUT);
  pinMode(GLEDPIN, OUTPUT);
  pinMode(BLEDPIN, OUTPUT);
  pinMode(wakePin, INPUT);

  attachInterrupt(0, wakeUpNow, CHANGE);
}

void sleepNow()         // here we put the arduino to sleep
{

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin

    attachInterrupt(0,wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the
                             // wakeUpNow code will not be executed
                             // during normal running time.

}

void loop()
{

    digitalWrite(GLEDPIN, HIGH); //set green led high

  times = millis();

  if(times>=1200)
  {

    digitalWrite(GLEDPIN, LOW); //Reset the LED's
    digitalWrite(BLEDPIN, LOW);
    digitalWrite(RLEDPIN, LOW);
    sleepNow();
  }
}


texts: Can I control my Arduino using just a 2.4GHz Wireless Transceiver and a wireless Xbox 360 controller?

texts:
I want to control my Arduino using my wireless Xbox 360 controller. I've been looking up tutorials, and they all seem to recommend using a USB shield and the Xbox 360 wireless receiver.

I don't own either of those things, but I do own a 2.4 GHz wireless transceiver. Can I use it to listen to what buttons are being pressed on the controller? For example, if I press the A button on the controller, can I make an LED turn on?


texts: SoftwareSerial.h alternative with AVR (Two Serial/UART ports in atmega328p)

texts:
Arduino pins can be used as UART using the SoftwareSerial.h library. Is there any alternative for AVR?

I need more than one serial port on a ATmega328P, but i don't use Arduino.

SoftwareSerial.h is tied to Arduino.h and Arduino pins. I do not use Arduino, i use avr-gcc with atmega328p and atmega8.


texts: What's the best way to control a USB-powered desk light

texts:
I recently bought a USB-powered desk light. Is it possible to control (turn on/off) it with the Arduino Uno? The desk light has 3W so needs 600mA.

Should I connect the USB wire with the 5V pin of the Arduino (which can spend up to 800mA) or should I use an external USB power supply ?
How to control the light when using an external USB power supply ?


texts: HC-SR04 distance measuring without delay?

texts:
I am using the HC-SR04 ultra sound sensor for Arduino. I have used the following code to calculate distance and it works perfectly.

  long duration;
  digitalWrite(trigger, LOW);
  delayMicroseconds(2);
  digitalWrite(trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigger, LOW);
  duration = pulseIn(echo, HIGH);
  distance = (duration/2) / 29.1;

However I want to use three more of these sensors, for a total of four. This block of code will be called every time I want to find the distance of one of the sensors. I am worried however that delayMicroseconds() pauses the entire program and that I cannot perform other tasks in while the sensors are working (e.g. driving wheels, it's a robot). The following code is object oriented for each sensor.

class distSensor{
   int trigPin;
   int echoPin;
   int distance;

   //Will be used in timer
   unsigned long previousMillis;

   public:
   distSensor(int tPin,int ePin){
   trigPin = tPin;
   echoPin = ePin;

   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);

   previousMillis = 0;
 }

 int calculateDistance(){

  //records time since program start
  unsigned long currentMillis = millis();

  long duration;
  digitalWrite(trigPin, LOW);

  //check if the previous time the method was called is greater than the interval of 2
  if(currentMillis - previousMillis > 2){
    digitalWrite(trigPin, HIGH);
    previousMillis = currentMillis;
  }

  //check if distance between current time and previous time it was called is greater than interval of 10.
  if(currentMillis - previousMillis > 10){
      digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  }
  return distance;
 }
};

In the calculateDistance() method I am trying to do the same thing as the first code but without delay() and instead a timer. But when I run the program it does not work and distance is read as 0. Can anyone help me rewrite the HC-SR04 code from the start that doesn't delay the whole program?


texts: I have some unused pins, should I connect them together and to the ground or leave them floating?


texts: Digital pin input stays high after receiving a high signal

texts:
I don't know why but when a pin set to input mode receives a high signal, then a low signal, it stays high for a seemingly random amount of time.

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
int thermPin = A5;
int relayPin = 9;
int upButton = 10;
int downButton = 11;
int rawVoltage;
float mv;
float desiredTemp = 20.5;
float currentTemp = 20;
long newSetTime = millis();
long oldSetTime = newSetTime;
long newUpPushTime = millis();
long newDownPushTime = millis();
long oldUpPushTime = millis();
long oldDownPushTime = millis();
int mainDelay = 600;
int flashDelay = 600;
boolean isSetting = true;

void drawCurrentTemp(){
  lcd.setCursor(0, 1);
  lcd.print(currentTemp);
}

void drawDesiredTemp(){
  lcd.setCursor(12, 1);
  lcd.print(desiredTemp);
}

void drawMainScreen(){
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("TEMP");
  lcd.setCursor(12, 0);
  lcd.print("SET");
  drawCurrentTemp();
  drawDesiredTemp();
}
String setString = "SET";
void flashSet(){
  if(newSetTime - oldSetTime > flashDelay) {
    if(setString == "SET"){
      setString = "   ";
    }else{
      setString = "SET";
    }
    lcd.setCursor(12, 0);
    lcd.print(setString);
    oldSetTime = millis();
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(relayPin, OUTPUT);
  pinMode(upButton, INPUT);
  pinMode(downButton, INPUT);
  drawMainScreen();
}

void checkInput(){
  if(digitalRead(upButton) == HIGH){
    newUpPushTime = millis();
  } else {
    oldUpPushTime = millis();
  }
  if(digitalRead(downButton) == HIGH){
    newDownPushTime = millis();
  } else {
    oldDownPushTime = millis();
  }
  long upButtonTimePushed = newUpPushTime - oldUpPushTime;
  long downButtonTimePushed = newDownPushTime - oldDownPushTime;
  if(upButtonTimePushed > 1000 && downButtonTimePushed > 1000) {
    oldDownPushTime = millis();
    oldUpPushTime = millis();
    if(!isSetting){
      isSetting = true;
    } else {
      isSetting = false;
      drawMainScreen();
    }
  }
  if(isSetting){
    if(digitalRead(upButton) == HIGH) {
      desiredTemp +=0.5;
    } else if(digitalRead(downButton) == HIGH) {
      desiredTemp -=0.5;
    }
    drawDesiredTemp();
  }
}

void loop() {
  newSetTime = millis();
  if(isSetting) {
    flashSet();
  }
  checkInput();
  Serial.println(digitalRead(upButton));
}


texts: always detects same pin as HIGH even when its not connected

texts:
Im practicing with an arduino UNO board (I'm a begginer) and I'm trying to turn some LED's on depending on which analog pin is connected to 5V.
Here's my code:
int statusLed = 11;
int out1 = 2;
int out2 = 3;
int out3 = 4;
int out4 = 5;
int in1 = A0;
int in2 = A1;
int in3 = A2;
int in4 = A3;
int statusLedBrightness = 3;
int incBrillo = 3;
int fadeDelay = 5;

void blinkFade(int pin){
  analogWrite(pin, statusLedBrightness);
  statusLedBrightness = statusLedBrightness + incBrillo;
  if (statusLedBrightness <= 0 || statusLedBrightness >= 255){
    incBrillo = -incBrillo;
  }
  delay(fadeDelay);
  }

void wait(){
  digitalWrite(out1, LOW);
  digitalWrite(out2, LOW);
  digitalWrite(out3, LOW);
  digitalWrite(out4, LOW);
  blinkFade(statusLed);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(out1,OUTPUT);
  pinMode(out2,OUTPUT);
  pinMode(out3,OUTPUT);
  pinMode(out4,OUTPUT);
  pinMode(in1, INPUT);
  pinMode(in2, INPUT);
  pinMode(in3, INPUT);
  pinMode(in4, INPUT);
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (analogRead(in1)>=500){
    Serial.println("1: ");
    Serial.println(analogRead(in1)); //Print "1" and the read of pin A0
    turnOff();
    digitalWrite(out1,HIGH);
  }
  else if (analogRead(in2)>=500){
    Serial.println("2: ");
    Serial.println(analogRead(in2));//Print "2" and the read of pin A1
    turnOff();
    digitalWrite(out2,HIGH);
  }
  else if (analogRead(in3)>=500){
    Serial.println("3: ");
    Serial.println(analogRead(in3));//Print "3" and the read of pin A2
    turnOff();
    digitalWrite(out3,HIGH);
  }
  else if (analogRead(in4)>=500){
    Serial.println("4: ");
    Serial.println(analogRead(in4));//Print "4" and the read of pin A3
    turnOff();
    digitalWrite(out4,HIGH);
  }
  else{
    Serial.println("Stand By");
    wait();
  }

}

The problem Im having is when I connect a wire from 5V to any analog pin (A0 to A3) it always runs this segment of code:
Serial.println("1: ");
Serial.println(analogRead(in1));
turnOff();
digitalWrite(out1,HIGH);

By my understanding it's detecting as if it always was A0 the one that is connected to 5V but i dont understand why is this happening or how to solve it.
This is a screen capture of serial monitor when 5V is connected to pin A2. It should print "3:" and the reading
[]
1


texts: How to automatically reset the nrf24l01+ with code?

texts:
I have two separate nrf24l01+ connected to two different Arduino UNOs, one as TX and the other as RX. The problem is the connection stops after a while between them.

On the Arduino COM screen I have noticed these things:

TX Side: Completely Frozen (Transmission Stops).
RX Side: Continuously receives the last data repeatedly.

The problem is solved temporarily when the TX MCU (hence the nrf) is restarted .Sometimes even after restarting the TX MCU the RX stops responding and I have to restart the RX as well. Therefore I am trying to find a way to reset my nrfs automatically using software when this situation occurs.


texts: How can I get Serial.print to print a variable thats a char?

texts:
I'm trying to write a function as part of my code, and the function basically has to write the name of a parameter, but I can't get it to print properly to the screen. Here is what I've got:

void dataprint(char parameterName, float dataNum, char unitName);
{
 Serial.print(",");
 Serial.print(parameterName);
 Serial.print(",");
 Serial.print(dataNum);
 Serial.print(",");
 Serial.print(unitName);
}

In the actual program part I have something like this:

char temp = "temperature";
float t = tempsensor.readTempC(); // just some number that comes from sensor
char unit = "C";
dataprint(temp,t,unit);

Right now in the serial monitor I get a question mark or something like that instead of the name I have saved in parameterName or unitName. I want this function to print the same way something like this would show up:

Serial.print(",");
Serial.print("temperature");
Serial.print(",");
Serial.print(c);
Serial.print(",");
Serial.print("C");

Thanks in advance for any help.


texts: Arduino Wall Wart and Relay Board Power Supply

texts:
I am relatively new to Arduino, and have been doing a project to trigger an LED/alarm when movement is detected to be over a certain threshold value. I am using an Arduino Uno, an LED/buzzer (https://www.adafruit.com/product/2994), an MPU-6050 (https://playground.arduino.cc/Main/MPU-6050), and a 4 channel relay board (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/ - sorry it's not very descriptive).

The LED/buzzer needs a 12V DC power supply, and I am using a wall wart to supply it. I am wondering how I am supposed to hook everything up - everything online tells me that the LED needs to be connected not only to the relay board, but to a power supply as well. However, my power supply is to the Arduino itself.

Based on the following picture, I would think that I would need to take the ground wire of the LED to the power source itself, then connect the power source to the relay board Common input.

Here is the circuit without the external power, using a small LED:

And here is the current setup (note that the cables were initially shifted over by 1 on the analog input, but I have fixed that since):

Is there a way to use the wall wart as the power supply? Do I even need the relay board?


texts: ArduinoDue - Matlab: SerialUSB.write() sends ASCII?

texts:
I'm trying to get some binary data from an Arduino Due to Matlab.

Basically this is the setup:

Due:

byte usbMsg[33]= {0};
// filled with dummy as example
usbMsg[1] = '00000001';// in[3];
usbMsg[2] = '00000001';//in[4];
usbMsg[3] = '00000001';//in[5];
.
.
.
SerialUSB.write(usbMsg, 33);

And on the Matlab side, I open the corresponding COM port and use a command like this one:

 a = fread(serialPort,3)

this gives me:

 a =

    49
    49
    49

which is the ASCII representation of the data I sent.

Can anyone explain to me why this happens and what I could do? As I understood serial.write sends binary data and fread reads binary data.


texts:
Working on a arduino script where I am right now entering manually the value with the URL, but wondering how to do it with a int in a loop.

This is the url and how it works now:

student.cs.hioa.no/~s180343/updatedb.php?verdi=25

Code:

#include <Process.h>

void setup() {
  // Initialize Bridge
  Bridge.begin();

  // Initialize Serial
  Serial.begin(9600);

  // Wait until a Serial Monitor is connected.
  while (!Serial);
  Serial.println("Ready");

  // run various example processes

}

void loop() {
   runCurl();
   delay(10000);
}

void runCurl() {
  // Launch "curl" command and get Arduino ascii art logo from the network
  // curl is command line program for transferring data using different internet protocols
  Process p;        // Create a process and call it "p"
  p.begin("curl");  // Process that launch the "curl" command
  p.addParameter("student.cs.hioa.no/~s180343/updatedb.php?verdi=25"); // Add the URL parameter to "curl"
  p.run();      // Run the process and wait for its termination

  // A process output can be read with the stream methods
  while (p.available()>0) {
    char c = p.read();
    Serial.print(c);
  }
  // Ensure the last bit of data is sent.
  Serial.flush();
}


texts: Do I need Kalman Filter after I read DMP data on MPU6050?

texts: In my project I need to use as noiseless as possible data from a MPU6050, I do have some nice DMP data, what will happen if I apply Kalman filter above it? Will I get more noiseless data? Or will it become unreliable anymore? Are there any benefits to do that ?


texts: How does arduino fetch instruction string from sms and execute?

texts:
I am working on a project in which i have to send commands using sms (GSM shield) to the arduino uno to control dc motor. What i want to know is that how can i define the instruction strings that i can send in form of sms and arduino uno reads it and executes it.

P.S. I am a total beginner at arduino coding so please help me out.


texts: No Websockets Server for Arduino mkr1010?

texts:
I've seen some interesting explanations on using websocket comms on mkr 1010 but it's always handling the mkr 1010 as the client and the server being always a computer or some other "non-arduino" server . I'm working on a system with several mkr 1010's in a master/slave setup and bidi comms i.e. i want to use one of the mkr's as a server (does the calculations etc.) and the other as clients (get result from calculations ans send back sensor info). I did not found any library or example of websocket server for mkr1010. I found it for ESP systems. Please help as i tried my bidi comms with webclient and webserver using http but not good enough for my applicaton (not realy bidi).
thanks a lot !


texts: I can't see any readings from my pulsesensor what can I do?

texts:
I have been using NodeMcu board for my project with a pulse sensor, DH11 sensor, and temperature sensor.
Everything has worked well in spite of the pulse sensor. It doesn't show any readings that always printing with 0 values in my serial monitor I have conected the wire as well and the code also has compiled well. but the sensor doesn't read anything it still remaining as 0 values.
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

//  Variables
const int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
                               // Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
                               // Otherwise leave the default "550" value.

PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

void setup() {

  Serial.begin(9600);          // For Serial Monitor

  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
   if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }
}

void loop() {

 int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
                                               // "myBPM" hold this BPM value now.

if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
 Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
 Serial.print("BPM: ");                        // Print phrase "BPM: "
 Serial.println(myBPM);                        // Print the value inside of myBPM.
}

  delay(20);                    // considered best practice in a simple sketch.

}


texts: Accel Stepper help, stepper not going backwards

texts:
So my question is that I am trying to use a arduino library called Accel Stepper to control a stepper motor, I made code that makes the stepper motor move one rev clockwise and then one rev counter clockwise

however as i run the code, the motor has no problem going clockwise, however when it comes to reversing the shaft of the motor stays still and doesn't move while the whole motor itself vibrates, what could be my problem?

here is my code:

    // MultiStepper.pde
    // -*- mode: C++ -*-
    //
    // Shows how to multiple simultaneous steppers
    // Runs one stepper forwards and backwards, accelerating and decelerating
    // at the limits. Runs other steppers at the same time
    //
    // Copyright (C) 2009 Mike McCauley
    // $Id: MultiStepper.pde,v 1.1 2011/01/05 01:51:01 mikem Exp mikem $

    #include <AccelStepper.h>
    int user = 800;
    // Define some steppers and the pins the will use

    AccelStepper stepper2(AccelStepper::DRIVER, 9,8 );
    AccelStepper stepper3(AccelStepper::DRIVER, 4, 7);

    void setup()
    {

        stepper2.setMaxSpeed(1000);
        stepper2.setSpeed(300);

    }

    void loop()
    {
        // Change direction at the limits
      stepper2.moveTo(user);
      stepper2.setSpeed(300);
      stepper2.runSpeedToPosition();
      if (stepper2.distanceToGo() == 0){
        stepper2.moveTo(-stepper2.currentPosition());
        stepper2.setSpeed(300);
        stepper2.runSpeedToPosition();
      }

    }


texts: Android  HC-05  Arduino communication issue

texts:
My project involves Android (Samsung Galaxy 2) to Arduino (Uno) communication via HC-05.

HC-05 is connected to Arduino on pins 10,11 using SoftwareSerial lib.

I got this setup running for a while and was satisfied by the outcome - my bi-directional communication worked fine.

Issue:

I made a change to the communication protocol and now messages sent from Android to Arduino get corrupted. It happens under particular circumstances - when Arduino writes (streams) packets of data to Android and, at the same time, monitors the input from Android for a particular message which signals the end of communication. This message, when read from SoftwareSerial buffer, gets corrupted. This corruption is not consistent - it corrupts the packet in (seemingly) random way.

I've already run many tests and am pretty sure that this message is not corrupted on the Android side.

Questions:

Is there anything about HC-05 or SoftwareSerial lib which prevents
simultaneous bi-directional communication?
Can it be that input/output buffers interfere in some way?
How can I achieve reliable communication using the aforementioned HW and comm scheme?

P.S. I got pretty much code and am not sure what parts of it might be relevant to this issue. Will provide relevant parts per your request.

Thx


texts: Problem stacking ADS1292r ECG shield and Wifi shield on Arduino Uno

texts: I want to use ADS1292r ECG shield with Arduino Uno (Seeeduino V4.2) and store the data in an SD card through an Wifi shield. But the ADS1292r shield uses Digital pin 4 for "RESET" purposes, while the same pin is the "SD card select" pin for the WiFi shield. So if I stack all 3 of them, the SD card can't be initialized. Is there any way to solve this problem?


texts:
I have a somewhat large sketch that uses the Adafruit_ssd1306(I2C) library for a 128X64 LCD. The sketch is a designed to be an alarm clock. When I upload the sketch with out initializing serial, it works as designed. However if I do intialize serial:

Serial.begin(9600);

the program fails to run on my UNO. After many hours of troubleshooting I noticed I have several large char arrays that may be the culprit.

const char *menusDisplay[] = {"1. Alarm-is Off", "2. Month", "3. Hour", "4. Minute", "5. Exit", "6. Alarm Set", NULL};
const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec", NULL};
const int days[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

The months array as 12 elements. If I shorted it down to 2 elements and upload the programs with serial initialized, the program runs. At first I thought is was a memory leak in perhaps the Adafruit_ssd1306. But I also have another LCD library Adafruit_ssd1306syp that the issue occurred too. So that ruled out those libraries.

When I compile the sketch without Serial:

Sketch uses 16,846 bytes (52%) of program storage space. Maximum is 32,256 bytes.
Global variables use 737 bytes (35%) of dynamic memory, leaving 1,311 bytes for local variables. Maximum is 2,048 bytes.

With Serial:

Sketch uses 17,862 bytes (55%) of program storage space. Maximum is 32,256 bytes.
Global variables use 910 bytes (44%) of dynamic memory, leaving 1,138 bytes for local variables. Maximum is 2,048 bytes.

Any ideas of what may be going on? I would load the sketch but its very large. If needed, I can try to cut it down and reproduce the issue.


texts: Unable to use analog pins as digital inputs

texts:
I want to use the analog pin A7 as a digital input pin. As stated in the Arduino docs the analog pins can be configured in the same way like any other digital pin.
However, when trying to configure an analog pin as a digital input pin, I get unexpected behaviour:

Using a digital pin (e.g. D2) works as expected.
When using an analog pin (e.g. A7) the LED is lit after start-up without pressing the button and does not change/react to any button press.
Since the docs state, that analog pins can be configured as digital pins and used in the same way, this behavior seems to be kind of confusing.

See my attached snippet to reproduce/examine the issue:
// using pin 2 (D2) works as expected (LED is lit on button press only)
// const int buttonPin = 2;

// using analog pin 7 (A7 / pin 21) as a digital input is not working,
// LED is lit directly after start-up & does not react to button press,
// analog pins are generally usabable as digital inputs
// see https://www.arduino.cc/en/Tutorial/Foundations/AnalogInputPins
const int buttonPin = A7;

const int ledPin = 13;

int buttonState = 0;

void setup() {
  // button is connected to GND, so enable internal pull-up resistors
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
};

void loop() {
  // as we use internal pull-up resistors, logic HIGH & LOW are inverted
  buttonState = !digitalRead(buttonPin);
  if (buttonState) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
};


texts: Cannot write lock byte on Arduino Pro Micro

texts:
I have an Arduino Pro Micro, with atmega32u4 chip and a caterine bootloader. However, every time I (successfully) flash some program over the USB port, the /dev/ttyACM0 device disappears, and I cannot flash it any more over USB.

So I connect it to my stk500v2-compatible ISP programmer (MISO/MOSI/SCK go to pins 14,16 and 15 on the board; VCC,GND,RST to their counterparts). With this setup, I can flash a new Caterina bootloader onto it. The problem with flashing over the board's USB port stays, though.

So I tried to set the lock byte with the ISP programmer, which writes successfully, but then fails at verification:

> avrdude -p m32u4 -P /dev/ttyUSB0 -c stk500v2 -b 115200 -U lock:w:0x0F:m
...
avrdude: verification error, first mismatch at byte 0x0000
         0xcf != 0x0f

Is my assumption correct that the disappearing bootloader is caused by the wrongly set (un-)lock bits? If yes, why can't I set the lock byte via ISP?


texts:
I have ESP32 connected to TZT servo SG90.
This is the code
#include <ESP32Servo.h>
#define TURN_TIME 175

Servo myservo;  // create servo object to control a servo
// 16 servo objects can be created on the ESP32

int pos = 0;    // variable to store the servo position
// Recommended PWM GPIO pins on the ESP32 include 2,4,12-19,21-23,25-27,32-33
#define servoPin  17
#define MOTOR_1_PIN 22

void setup() {
  pinMode(servoPin, OUTPUT);
  Serial.begin(9600);
    // Allow allocation of all timers
    ESP32PWM::allocateTimer(0);
    ESP32PWM::allocateTimer(1);
    ESP32PWM::allocateTimer(2);
    ESP32PWM::allocateTimer(3);
    myservo.setPeriodHertz(50);    // standard 50 hz servo
    // using default min/max of 1000us and 2000us
    // different servos may require different min/max settings
    // for an accurate 0 to 180 sweep
}

void loop() {

  myservo.attach(servoPin, 700, 2500); // attaches the servo on pin 18 to the servo object
  myservo.write(0);
  delay(TURN_TIME);
  for(int i =0; i<180; i++)
  {
    myservo.write(i);
    delay(TURN_TIME);
  }
  delay(3000);
  for(int i =180; i>0; i--)
  {
    myservo.write(i);
    delay(TURN_TIME);
  }
  myservo.detach();
  delay(3000);

}

My servo starts rotating one way and reverse for few degrees, then after 5 seconds the servo starts rotating at one way forever..
I had no problems with arduino and nodemcu board. What should I change in the code?
EDIT: I have connected the servo with battery, they have common ground.
The pin on esp32 that I am using is G17. "#define servoPin 17" in the code


texts: Firmware for Atmega32u4 on the Arduino Uno Wifi Rev2 (causing upload issues)

texts:
I reprogrammed the Atmega32u4 on my Arduino Uno Wifi Rev2 in order to use it as a human interface device, but I am now having difficulty programming the 4809 (through the 32u4 over UPDI) with the Arduino software. I have tried reprogramming the 32u4 with medbg_updi.hex from Atmel Studio and also Xplained Yourself Firmware from https://hackaday.io/project/162372-xplained-yourself.
I have had some success writing some smaller applications to the 4809 but when I try to program larger applications (which used to work before I fiddled with the 32u4), I now get verification error saying that there is a mismatch.
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0200
         0x08 != 0x0c
avrdude: verification error; content mismatch
avrdude: jtag3_edbg_signoff(): unexpected response 0x03, 0x80

When cross referencing with other working Uno Wifi Rev2 boards, they have
ICE firmware version: 1.19 (rel. 57)

while I now apparently have
ICE firmware version: 1.13 (rel. 43)

I do not see any place to find the updated/original firmware which came with my arduino. My thought is that the firmware is not available for direct download because it may be licensed from Microchip (Atmel) and not distributed/proprietary...
Please assist me if possible in restoring the full functionality of my Arduino Uno Wifi Rev2. Any insights would be appreciated.


texts: Arduino support package in matlab PROBLEM

texts:
i have installed the Arduino support package in matlab  , and i have all blocks that come with it in my simulink
the problem is that when i try to establish a serial communication i got smth like this :

    a = arduino

    Undefined function or variable 'arduino'.

thanks :)
nb : i'm using arduino uno


texts:
I'm having problems with using Arduino Leonardo PWM outputs (I'm actually using YUN board).

I need 4 PWM outputs that generally have the same base frequency of around 10 to 20 Hz or so.

I'm using timer 1 (A-pin-9,B-pin-10,C-pin-11) and timer 4 (A-pin-13)

I get pins 9,10,and 13 PWM output working decent, but for some reason pin 11 PWM frequency is much much higher.

Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Here is my code can anybody see anything wrong? thanks!

    #define PWM_4A_PIN  13
    #define PWM_1C_PIN  11

    #define PWM_1B_PIN  10
    #define PWM_1A_PIN  9

    void setup() {
     TCCR1B = TCCR1B & 0b11111000 | 0x05;
     TCCR4B = TCCR1B & 0b11110000 | 0x09;
     analogWrite(PWM_4A_PIN,128);
     analogWrite(PWM_1C_PIN,128);
     analogWrite(PWM_1B_PIN,128);
     analogWrite(PWM_1A_PIN,128);
    }

    void loop()
    {
    }


texts: Adafruit Motor Shield and Bridge Library for Yun Shield

texts:
I am using the Leonardo board with the Adafruit Motor Shield v2, 2 steppers and the Yun Shield. The yun shield and steppers all run harmoniously, however, as soon as I do Bridge.begin() and anything that accesses the Yun shield Bridge library to access the console, the steppers stop running. Is this to be expected and are there any solutions?

Thanks


texts: Is a power off sufficient to avoid problems with the Watchdog on Arduino Mega 2560?

texts:
I'd like to offer some context about what I'd like to do because I might have misundertood something.

I'm trying to reduce power consumption on my device, an Arduino Mega 2560, and I've found this library

https://github.com/rocketscream/Low-Power

which uses the Watchdog to put Arduino on power saving for a predetermined interval of time; after that it reactivates what has been disabled and let the program continue its flow.

I searched for more information about the Watchdog and I found out several warnings about dealing with Watchdog on an Arduino Mega 2560, stating that it would only work with a modified bootloader:
This scared me a bit because I'm not very keen on risking to brick my Arduino (I absolutely need it to work on the next few days).

Now, I only have two Arduino Mega 2560 at my disposal and if I'm not mistaken, flashing the bootloader on an Arduino Mega 2560 using another Arduino Mega 2560 as a programmer can't be done because the procedure ends with errors:

( see http://forum.arduino.cc/index.php?topic=126160.0 )

Hence my most important question: if I test the watchdog functionality on my code (the sketch) and the Arduino happens to continually reset, can I fix the situation by powering off the Arduino?

(if you can help with my other issues as well, I'd be very grateful, I'm not sure I completely understood how these things work)


texts:
I have a fixed roof light in my room that came with a remote control that can be fully taken apart. The remote control can switch the lights on or off using a radio system. I was wondering if there was any way to use my Arduino to control the remote control (through wires) to control the lights. I do not have any Arduino radio components so it would still need to go through the original remote. I have taken the remote apart and this is what it looks like:

http://go.hma-uk.org/dlt

The buttons are as follows: the top two (K1 & K2) buttons is to turn on/off a coloured LED but these are not important to me. The button K3 is to turn on/off the main light (I want the effect of this button being pressed to be created using the Arduino) and the button K4 is to turn all lights on/off.


texts: NodeMCU v2 with MH-Z19B CO2 sensor UART read problem

texts:
I'm trying to read data from MH-Z19B sensor to NodeMCU v2 board with a simple circuit like this.

Some key points, which could be not that obvious from picture:
 - sensor has separate power supply of 4 AAs, providing ~5,5V
 - sensor's TX connected to GPIO15 (TX D2) of NodeMCU
 - sensor's RX connected to GPIO13 (RX D2) of NodeMCU

And here is my sketch:

const byte readCommand[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; // according to datasheet
unsigned char response[9];

void setup() {
  // according to datasheet, sensor uses 9600 baud, 8 databits and 1 stopbit
  // with parity NONE, which I believe corresponds to default config SERIAL_8N1
  Serial.begin(9600);
}

void loop() {

    //  ... check if it is time to measure

    Serial.swap(); // switch to sensor

    Serial.write(readCommand, sizeof(readCommand));

    memset(response, 0, sizeof(response));

    int attempts = 5;
    int available = Serial.available();
    while(available < sizeof(response) && attempts > 0) {
        delay(100);
        attempts--;
        available = Serial.available();
    }

    Serial.readBytes(response, sizeof(response));

    Serial.swap(); // switch back to console

    // print out the response in hex
    for (int i = 0; i < sizeof(response); i++) {
      Serial.print(String(response[i], HEX));
      Serial.print("   ");
    }

    // ...process the response according to protocol
}

The Problem

For some reason after sending command to serial I get an answer exactly the same as command is although the structure of answer expected to be different. Of course datasheet says nothing about situations like this.
Expectation

ff 86 .. .. 0 0 0 0 CRC

Reality (same bytes I sent as a command)

ff   1   86   0   0   0   0   0   79

Other notes:
 - I got exactly the same when tried to use SoftwareSerial with D1 & D2 pins
 - connecting TX to RX respectively on both sensor and MCU results in reading failure
 - I tried to pull everything while available from serial, there are only my expected 9 bytes
 - my soldering skills are far from ideal, but I'm pretty sure tx/rx on the sensor are connected properly

I'm new to all this stuff, so it is completely possible that there is ridiculously silly, but crucial mistake, so would appreciate any help on this. And I understand that sensor also has additional interfaces to obtain the value, but as I mentioned I'm a newbie and wanted to familiarize myself with UART as this is something new for me.

UPD 1:
I didn't use level conversion for sensor output as datasheet says:

Assuming this I thought that sensor provides logical level conversion itself. Did I get it wrong?

UPD 2:
I got back to proper TX - RX connection just to check out what is going on exactly to describe that "reading failure" problem with more details. It seems that Serial.available() returns 0 after I send command so this loop gets stopped after 5 attempts:

while(available < sizeof(response) && attempts > 0)


texts: Adding button which resets to top of void

texts:
I'm quite new to Arduino and the programming of the board, but I wanted to have a go at making a traffic light based on an example I found online.

The example supplied a simple layout which I roughly copied with the components I had.

I then created the following code to mimic the traffic lights of my local area.

int red = 13;   int yellow = 12;   int green = 11;

void setup(){
    pinMode(red,OUTPUT);
    pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
}

void loop(){
    changeLights();
}

void changeLights(){
    // red on, other off for 3 seconds
    digitalWrite(green,LOW);
    digitalWrite(yellow,LOW);
    digitalWrite(red,HIGH);
    delay(3000);

    // red on, amber on,green off for 3 seconds
    digitalWrite(green,LOW);
    digitalWrite(yellow,HIGH);
    digitalWrite(red,HIGH);
    delay(3000);

    // red off, amber off,green on for 3 seconds
    digitalWrite(green,HIGH);
    digitalWrite(yellow,LOW);
    digitalWrite(red,LOW);
    delay(3000);

    // red off, amber on,green on for 3 seconds
    digitalWrite(green,HIGH);
    digitalWrite(yellow,HIGH);
    digitalWrite(red,LOW);
    delay(3000);
}

What I'm wanting to achieve next is a button which resets the code back to the top of void changeLights.
I assume I would be able to do this using a push-to-make switch, but I'm not sure how to incorporate it into my circuit or if it is even possible to reset using this.


texts: Disturbed digital out at 4Mhz on Arduino NANO

texts:
I've written a simple program - it generates signals over Port D at 4 MHz:

#include <Arduino.h>

int main(void) {

    DDRD = B11111111;
    PORTD = B00000000;

    while (true) {
        PORTD = 0;
        PORTD = 5;
        PORTD = 10;
        PORTD = 15;
        PORTD = 20;
        PORTD = 25;
        PORTD = 30;
        PORTD = 35;
        PORTD = 40;
    }
    return 0;
}

and this is the signal coming out on D4:

I've modified the program by inserting NOP after each assignment to POTRD:

#define NOP __asm__ __volatile__ ("nop\n\t")

int main(void) {

    DDRD = B11111111;
    PORTD = B00000000;

    while (true) {
        PORTD = 0;NOP;
        PORTD = 5;NOP;
        PORTD = 10;NOP;
        PORTD = 15;NOP;
        PORTD = 20;NOP;
        PORTD = 25;NOP;
        PORTD = 30;NOP;
        PORTD = 35;NOP;
        PORTD = 40;NOP;
    }
    return 0;
}

and now signal looks fine, but frequency is limited to 800 KHz:

What is the reason for interference at 4 MHz? Is there a limitation to maximal frequency on digital out? I do not really need it for some particular project, just wanted to know it.

I've asked this question on stackoverflow, but then I've discovered this dedicated forum so... I've decided to try it out ;)


texts: LED won't turn on and serial monitor won't display values

texts:
I am trying to use my Arduino to record some values from a photo-resister. The idea is when a character other than g is read the LED will turn on and 512 values will be recorded.

When I type in a character in the serial monitor whether it is g or not it just says 1 or 0 but doesn't not provide me with the values I need from the photo-resistor. My code is as follows:

int timeOut = 60000;
int pollTime = 0;
int time = 0;
unsigned long startTime = 0;
unsigned long endTime = 0;
int x = 0;
int Vs[512];
int analogPin = 0;

void setup() {
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  while (!waitFor('g', 200, 60e6)) {}
  analogWrite(9, 128);
  startTime = micros();
  for (x = 0; x < 512; x = x + 1)  {
    Vs[x] = (analogRead(analogPin));
  }
  endTime = micros();
  for (int x = 0; x < 512; x = x + 1)  {
    Serial.println(Vs[x]);
  }
  Serial.println(endTime - startTime);
}

void loop() {
}

boolean waitFor(char in, int pollTime, int timeOut)  {
  boolean done = false;
  char charWait;
  time = micros();
  while (time < timeOut)  {
    if (Serial.available())  {
      charWait = Serial.read();
      done = (charWait == in);
      Serial.println(done);
    }
  }
}


texts: Establishing wireless comm. between PC and arduino pro micro to exchange speech and gyro data

texts: I have a client project to make a wireless head-mounted mouse. What wireless module should I use so that I can exchange data between my laptop and the arduino pro micro through the USB port like a wireless mouse? I am using an MPU6050 accelero+gyroscope sensor for cursor movement and Electrohouse Voice Recognition module V3.1 for speech recognition. To exchange such data between PC and arduino, I found a lot of options. Hence, I am confused. Please help me decide what to use so that cost efficiency and effectiveness can be acheived. Should I use bluetooth, RF shield , XBEE or any other module?


texts:
So I spent a bit trying to figure the wiring and I THOUGHT I had it working but something interesting happened. Displaying works for only the numbers 1, 3, 4, 7, 8, and 9, but are weird when it comes to the numbers 2, 5, 6. I am unsure why this is happening and tbh I am pretty new to arduino.

This is how it displays 2222:

Here is the code:

#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {

byte numDigits = 4;

byte digitPins[] = {2, 3, 4, 5};

byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};

sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);

sevseg.setBrightness(60);

}

int timer = 1000;
void loop() {

  sevseg.setNumber(2222);

  sevseg.refreshDisplay(); // Must run repeatedly

}

Any ideas on how this might be happening?


texts: I am trying to use a DC power supply. I am thinking whether I can use this power supply to provide power for Sim800L module. After some research, I gathered that the Sim800L module requires a max current of 2A during GPRS transmission at 3.8-4.2 V (4.0 recommended). With the power supply I can easily configure the voltage at 4.0V. My question is: for this setup, do I need a DC-DC Buck Converter as in this one for regulation/step-down (not sure which)?


texts: How to send chars and values at the same time from processing to Arduino

texts:
i have been trying to set Builtin LED frequency from arduino and turn it on and off .

I have created an interface with knobs and buttons in processing . I want to set delay between ON and OFF with 1 knob and OFF and ON delay with another knob . And button blinks the led at given frequency

In arduino i have tried something like this :

if(Serial.available() >0){
char val=Serial.read();
switch(val)
{
  case 'c':
  theValue=Serial.read();
  break;
  case 'd':
  theValue1=Serial.read();
  break;

case 'r':
digitalWrite(13,HIGH);
delay(theValue);
digitalWrite(13,LOW);
delay(theValue1);

break;
}

}

In the processing :

  public void Blink(){
   myPort.write('r');
 }

 public void knobON(int theValue){
   myPort.write('c');
   myPort.write(theValue);
 }

 public void knobOFF(int theValue1){
   myPort.write('d');
   myPort.write(theValue1);
 }

Can you help me on what should i do ?


texts:
I'm very new to electrical engineering and I'm trying to read microphone input with Arduino Nano. I've made a separate microphone module (based on this example) and plugged it into Arduino like this:

Unfortunately it was the last time my Arduino was working. It's no longer displayed as a connection, and acts "randomly", so I think my microphone toasts controller for some reason. Here are some more pictures and a scheme of my mic module, could someone explain what am I doing wrong?

simulate this circuit – Schematic created using CircuitLab

R1 - CR1/4W 10 (brown,black,black,gold)

R2 - CR1/4W 2KO (red,black,red,gold)

I have no education in electrical engineering, so I'm not sure about the correctness of this schema of units, just pasted what's written on the pack


texts: String use in arduino IDE (this question for understanding)

texts:
I'm using arduino several month now, And i don't understand when i can use the arduino object of String. I'll explain, I read a lot and the it's look like that this object is a good way to read/write and use strings, But everywhere they say that this object take a lot of RAM. So i made some project, And almost in all of them the String object not work as i expected. When i check the RAM in my projects i see that when my usage of RAM is greater then 65% the string object start to do problems. Because of this i stop use the string object and use only char arrays.

So my question is:

How can i know when i can use String from the beginning?
there is a way to change from char array to string or vase versa easily (i know this is completely different logic)?
How can i avoid the memory problems with the String object?

All this questions come from that the String object is very effective and easy to use and i want to use it, But i'm fear from RAM problems so i'm not using it.

Thank you very much for reading all this, Hope you can help me!


texts: How to store gps values in EEPROM arduino?

texts:
I have two successfully working individual programs,
1.GPS coordinate extract program.
2.EEPROM saving and reading program.
now all I want to do is combine them both, whenever GPS location is updated ,I want to save that latitude data to EEPROM memory repalcing the previously saved data, but I guess my program is unable to save it,its just showing blank spaces when reading EEPROM,please help me guys..here is my code.

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#define RXPin 8
#define TXPin 9
#define GPSBaud 9600
#define ConsoleBaud 9600

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

// The TinyGPS++ object
TinyGPSPlus gps;
#include <EEPROM.h>
int address = 0;
int read_value = 0;
char data;
void setup()
{
  Serial.begin(ConsoleBaud);
  ss.begin(GPSBaud);
  Serial.println("Previous value stored :");
  for(address = 0; address < 25; address ++)        // read the entire EEPROM memory
  {
    read_value = EEPROM.read(address);
    Serial.write(read_value);
  }
  Serial.println("\n");

}

void loop()
{

  while (ss.available() > 0)
    gps.encode(ss.read());

  if (gps.location.isUpdated() || gps.altitude.isUpdated())
  {
    Serial.print("Location: ");
    Serial.print(gps.location.lat(), 6);
    Serial.print(",");
    Serial.print(gps.location.lng(), 6);
    Serial.println("\n");

    data=(gps.location.lat(), 6);

    for(address = 0; address < 25;  )
    {
      EEPROM.write(address, data);
      address ++;
    }
  }
}


texts: Generate 1khz square signal with Arduino Mega

texts:
I want to generate a 1khz square signal with an Arduino Mega.
I have read the MCU contains several timers.
What i want to do is to configure one of this timers.
My first question is: Is there a way to automatically control an output pin from the timer, without having to execute any line of code in my arduino program ? Look at my code: i need to write a line in ISR(TIMER1_OVF_vect). Some MCU can do that but i did not find any information about it on documentation. (Some pins are connected on timer outputs, by hardware conception).
My second question is: What is wrong on my calculation on my code ?
I want 1khz and i get 990Hz
Here is what i've done:

Arduino Mega runs at 16Mhz = 16000Khz
I have set a /8 prescaler, so timer's frequency is 8000Khz
The frequency should by divide by two because i have 2 states (HIGH and LOW): 4000Khz
The interupt is fired when the counter reach 65536. So if i load 65536-1000 in TCNT1, the timer should count 1000 times in order to fire the interupt. So my frequency is 4000khz/1000 = 1khz.

What is wrong ?
Thanks a lot
void setup() {
  pinMode(14,OUTPUT);

  noInterrupts();
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 65536 - 1000;
  TCCR1B |= (1 << CS11);    // Prescaler clock / 8
  TIMSK1 |= (1 << TOIE1);
  interrupts();
}

ISR(TIMER1_OVF_vect)
{
  TCNT1 = 65536 - 1000;
  digitalWrite(14, digitalRead(14) ^ 1);
}

void loop() {

}


texts:
So I have created this project to have an LED blinking at a constant speed whenever the program is running. The first LED (green) will blink faster and faster the closer an object gets to the sensor. The second LED (Blue(is referenced in code as white)) should be blinking constantly. The LED (blue) is only blinking when my ultrasonic sensor has something in range. I would like to make it so it blinks no matter the circumstances.
This is probably something obvious Im missing - excuse my noob-ness
NOTE: if the picture of the circuit isnt correct (pins not being correct) know that it is correct in real life, this is what I get for doing a quick mock up and post at 1:00 AM
#include "DHT.h";

#define DHTTYPE DHT22   // DHT Type is DHT 22 (AM2302)
#define DHTPIN 7       // DHT-22 Output Pin connection
#define trigPin 5
#define echoPin 6
#define beepPin 12
#define scalingfactor 10
#define blueLed 11

#define ledPin2 10

float hum;    // Stores humidity value in percent
float temp;
float soundsp;
float soundum;
 DHT dht(DHTPIN, DHTTYPE);  // Initialize DHT sensor for normal 16mhz Arduino

int centi = 0;

const long erval = 500;

unsigned long previous = 0;
unsigned long lastduration = 0;
unsigned long duration = 0; //time it takes for sound to return
unsigned long maxtime = 2000;
unsigned long i = 1;  //variable to determine actual distance
unsigned long time2 = 0;
unsigned long time1 = 0;

void setup() {
  Serial.begin (9600);  //open monirot channel
  dht.begin();  //start temp and humidity sensor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(beepPin, OUTPUT);
  pinMode(blueLed, OUTPUT);
}

void calculate(){
      // Calculate the Speed of Sound in M/S in accordance with temp
    soundsp = 331.4 + (0.606 * temp) + (0.0124 * hum);

    // Convert to cm/us
    soundum = soundsp / 10000;
}

void logdistance() {
  digitalWrite(trigPin, HIGH); // send sound signal
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);  // stop sound signal
  duration = pulseIn(echoPin, HIGH);  // listen for sound signal
  centi = (duration* soundum)/2;   // determine delay of sound signal in one direction
  maxtime = scalingfactor * centi;  // change max time in accordance to the distance of the previous object
}

void beep() {
  digitalWrite(beepPin, HIGH);   // turn on the beep pin (or LED pin)
  delay(60);
  logdistance();   // run the log distance function again so we get accurate data
  if (time2 - time1 < 30) {  // delay based on how close an object is
    delay((60 - (time2 - time1)));
  }
  digitalWrite(beepPin, LOW);  // turn off beeper (or LED)
  i = 1;
    while (1) {
    if (i % 60 == 0) {
      logdistance();  // run my log distance funciton
    }
    delay(1);
    ++i;  // add one to i to report that we have recorded the distance
    if (i >= maxtime) { // dont report distanc if sound took longer than max time to return
      break;
      }
    }
}

void BlinkBlue (int interval){
   static long prevMill = 0;
   if (((long)millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(blueLed, !digitalRead(blueLed));
   }
}

void temps(){
  hum = dht.readHumidity();  // Get Humidity value
  temp= dht.readTemperature();  // Get Temperature value
}

void loop() {
  BlinkBlue(500);
  beep();

  temps();
  calculate();

  //print results
  Serial.print (duration);
  Serial.print("c. ");
  Serial.print(centi);
  Serial.print(" ");
  Serial.print(temp);
  Serial.println(" ");
}


texts: Motor shield causing problems with interrupts?

texts:
I am making a controller for a model railway turntable and I need to control a single DC motor and read a hall effect sensor. I have the hall effect sensor connected to pin 2 on my Uno (since 2/3 are the only pins that support interrupts) but whenever I turn the motor on it triggers the interrupt on pin 2 despite the fact that the motor PWM pin is on pin 11 and I have disconnected alternate PWM pin 3. This is with the official Arduino motor shield and an Uno.

I'm at a loss here, any ideas? I know it's not the motor triggering the hall effect sensor because I connected a resistor in place of the motor and it still happened.


texts: Arduino communicating back and forth with PHP server

texts:
I am researching to find the best method to work with in order to control the arduino from a web interface (hosted on a web server using PHP) and also sending data from arduino to webserver and save to mySql.

2 methods which I have found that a lot use are save the data to a text file or in the url.

Which is the best or are there any better methods?


texts: How can I create a power rail on my Arduino shield?

texts:
I have an Arduino that has 4 devices within an enclosure.  Each of the 4 devices needs 5 V and GND.  I have a shield with lots of unused pins (see photo).  I'd like to "bridge" one row of the pins to create a power rail, and I'd like to bridge another row to create a ground rail.

I think most people are using an external breadboard for this.  Also, I see that there is a shield that has power rails, but I don't have room for it.  I'm looking for a female header, or another way to bridge these unused pins.

Note: I'm not asking about wiring voltage in parallel or amperage consumption.


texts: Can a 12V sensor connected to a 5V output signal of an Arduino Uno

texts: I am doing a project for object detection. But my problem is I'm using a 12V photoelectric OMRON sensor to connect with 5V Digital PWM port 3 on Arduino using normal coding. Do I need an extra circuit to step down the voltage to 5V? Can it work because the only connection between the sensor and Arduino is the output signal, the VCC and Ground are from external power. Link to the datasheet Please help me