texts:
Background:

I have been working on an exoskeleton project with a group of friends, and I need help.  I made another post on the robotics.stackexchange site for the drive system: https://robotics.stackexchange.com/questions/4323/exoskeleton-drive-system-help.  You can also check out our first prototype on youtube: https://www.youtube.com/watch?v=NL_aCwJSRiE&feature=youtu.be

The device is going to be controlled by an iPad that we created via bluetooth.  We are using the adafruit bluefruitLE

We are attempting to control 4 motors (2 knee motors and 2 hip motors) from an Arduino Mega.  We will be using 2 Roboclaw 2x60A motor controllers.  We are trying to get the motors to mimic the graph (see attached).

The graph is in degrees per percent cycle (a gait cycle).  We are using 50 gait cycles per minute for tests but we hope to make it adjustable.
We can change percent cycle to time in milliseconds using dimensional analysis (ie) 50 cycles/min = 8.333x10^-4 cycles/ms  —->  1/8.333x10^-4 cycles/ms is approx. 1200 ms/cycle.  So if you multiply the cycle times 1200 you get millisecond for a certain percent of the cycle (ie) 0.5cycles(50 percent of cycle) * 1200ms/cycle = 600 ms.

We will have a position feedback system incorporated in the drive system but because it is a prototype and I wanted to make the code as versatile as posible I created a function: getDegrees(int jointNum), so if I change the position feedback system I only have to change the getDegrees method.

In order to mimic the graph we broke the graph up into sections.  Each section represents a different velocity.  We are going to run a correction algorithm so far we have just done the P in PID, we have used a modifier of 1.5.  Then we saved the value that the section ended on so next gait cycle when it runs that section the algorithm will start off closer to the target value.

My question:

I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.  While the device is running we need to be able to constantly check for a bluetooth message from the iPad.  The bluetooth messages come in via SPI from the adafruit bluefruitLE.

What I have done so far:

I have been able to run a single joint by using a while statement (ie)

int i = 0;
void loop(){
targetAngle = nextAngle[i]; //nextAngle is an array of points so nextAngle[0] through nextAngle[1] represents one section of the graph.
i++
if (getDegrees(1)< targetAngle){
double deg = getDegrees(1);
while (deg<targetAngle){
/*
*
*Execute drive code
*
*/
deg = getDegrees(1);
}else{
double deg = getDegrees(1);
while (deg>targetAngle){
/*
*
*Execute drive code
*
*/
deg = getDegrees(1);
}
}
}

The main problem with that code is its like using the delay() function instead of millis() is that it stops the program while its executing the code, and I cannot run multiple motors and check for bluetooth messages.

Major Challenges:

The drive commands must be based off of angle and not time.  It is ok if we tell it do 50 cycles per minute and it does 52 or 48 but its not okay if it only does 97% of the motion.

Possible solutions I have come up:

Using one arduino for each joint, and making them all slaves of a master arduino and the master arduino would act as the middle man sort of between the joints, making sure that they are synced up.  That way each arduino could use code similar to what I have already tried and confirmed to work.  But I would prefer to run it all from one arduino.

Conclusion:

I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.

Is this the right forum for this question?  Or is it more of a Stack Overflow or Robotics question?

Any help will be greatly appreciated,

--
Joel


texts: Any suggestions? (On running two programs within one Arduino maybe)

texts: Super duper noob here! Please help me out thanks!. So what I am doing right now for a project is to create a device that can read the EMG (muscle tension) in the body, and when it reads a specific number, an audio clip will be triggered to play. I already hooked up the Arduino board to this device that reads EMG successfully. Now my question is, to add the audio component to this device, what should I do? Can another program actually run on the same Arduino device? Is there an add on that I need to buy? (Perhaps some sort of Bluetooth device to connect to a Bluetooth speaker for the audio? )


texts:
I have a NodeMCU and a website (free website domain provided by http://www.hpage.com) and I have to send and receive some data (suppose a 8bit number) from the website to the NodeMCU via internet. The NodeMCU is connected to internet through WiFi hotspot of an Android phone.

Can anyone provide an example code? How can I address the NodeMCU from the website?
Does the NodeMCU need to be a server or just a client?

Thanks in advance for kind help.


texts:
So I installed libraries through the Arduino interface (Sketch > Include Library > Manage Library). Then I check: C:\Users\username\OneDrive\Documents\Arduino\Libraries, and I confirm the new libraries are there.

However, when I compile I always get the error that Arduino cannot find the library, no matter which one I try to import.

I'm on Arduino 1.8.5, Windows. What am I missing?


texts: Connecting to Alexa with FAUXMOESP library not detecting the device

texts:
I am using NodeMCU (ESP8266 12E) module from some days. I am trying to connect to Alexa for voice controlling. I have Amazon Alexa Echo 2 from which I am trying to discover my nodemcu as a smart home device.

Here is my sketch I am trying to use to detect.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <fauxmoESP.h>

fauxmoESP fauxmo;

const char* ssid = "myssid";
const char* password = "mypassword";

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

  fauxmo.enable(true);

  fauxmo.addDevice("light one");
  fauxmo.addDevice("light two");

// this is not able to detect .onSetState function I am not sure about the reason.

//  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {
//        Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);
//    });
}

void loop() {
    fauxmo.handle();

}

void wifisetup() {
  pinMode(2, OUTPUT);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  IPAddress ip(192, 168, 1, 243); // this 3 lines for a fix IP-address
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  IPAddress dns(192, 168, 1, 1);
  WiFi.config(ip, dns, gateway, subnet);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(10000);
    digitalWrite(2, HIGH);
    ESP.restart();
  }
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(2, LOW);
    Serial.println("");
    Serial.println("Your ESP is connected!");
    Serial.println("Your IP address is: ");
    Serial.println(WiFi.localIP());

    delay(100);
  }

}

I am using https://bitbucket.org/xoseperez/fauxmoesp library to do the setup. Alexa is not able to detect my device. Not sure whats the issue with this, but in the Serial Monitor I can see the logs which is showing that I am getting ping from Alexa to my ESP8266.

Taking an output pin is compulsory? I have tried that too although but no output found.

Thank you!


texts: Most compact way to power 5V Arduino boards?

texts:
So I have quite a few ideas for wearable devices using Arduino boards (mainly the Nano and the Micro clones). With that in mind, I want to determine what the best way to power an Arduino is, with compactness in mind (and cost too, of course). One single button cell battery does not supply enough power to the Arduino to power it properly. I can use these 2x button cell battery holders (6v) but they mainly ship only from China and, for some reason, are relatively expensive ($15 for 6 of them).

Does anyone know of a better and cheaper way of powering these Arduino boards, with wear-ability in mind?

Thanks! :)


texts:
I'm trying to set up my Arduino to send SMS messages using the SIM800L and AT Commands but for some reason, the message is never sent. I've spent so long trying various source code from different websites, I've bought and tried 3 different SIM800L chips and even tried a SIM808 chip but the problem is always the same...
I can confirm I have a network connection from the chip and it will receive messages.
I am using the code below to send the message. I've inserted my own phone number. When the message in the serial monitor shows, that's where it stops, which leads me to think it might be something to do with sending the character 26 over serial to end the message.
There is supposed to be a message ID returned at this stage to show the message was sent but it is not showing.
I've also tried converting the character 26 like this: (char(26)) but this character might be a red herring- I don't know.
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(11, 10); //SIM800L Tx & Rx is connected to Arduino #3 & #2

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

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

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

  mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
  updateSerial();

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

void loop()
{
}

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


texts:
I have loaded the Arduino IDE on Windows 10 32-bit on a 64-bit machine. This is my kids' laptop so they don't have admin privileges but, I installed it with admin privileges.

I have restarted the laptop, but the IDE does not start when I try to open it.  I am not signed is as administrator.

Any assistance would be greatly appreciated.


texts: Serializing data created by ATTiny85 for use on PC

texts:
Have an AES-128 implementation I'd like to install on an ATTiny85 for embedded use but need to come up with a way to communicate with it from a PC as you would do via Serial on Arduino Uno. For example, I'd like to stream 16 bytes of plaintext and get back 16 bytes of ciphertext (or signature hash, etc.).

The faster the transfer rate, the better obviously, but it would of course need to fit on the remaining space on an ATTiny85.

Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?


texts: Arduino for Weather and Air Monitoring: Casing and Power Source

texts:
I am intended to use Arduino to measure Temperature and Humidity (DTH11) and Gases Grove Sensor (Multichannel). Due to weather conditions in UK, I would to get your advice how to shield all of them in water proof box? Do you believe that using Polystyrene is useful?
Any recommended power source?


texts: How to implement the Arduino Extended Database library in a custom class?

texts:
I am struggling to implement a custom class that uses the Arduino Extended Database Library (EDB.h). The purpose of my custom class is to manage my application's internal database.

While searching for a solution I found this, which seems very relevant: the code and goal are the same as mine.

But my problem with that Q&A is that I am not able to implement the given solution as I don't fully understand the way it should be written.

For the sake of trying to give the best support for explanation, I upladed the code below. Feel free to explain me how to modify it.

Thank you.

EDIT: Following duplicate comments, I'll try to be more precise in my question.


texts:
I usually use Platformio as IDE for my Arduino projects. I like it as an editor, but I don't like its serial monitor feature. So I often open the Arduino IDE in background to use its serial monitor, but this has some drawbacks (including a significant increase in my computer's CPU usage and battery consumption).

Is there an Arduino-compatible serial monitor application that just works as a serial monitor (and not also as an IDE)? I'm most interested in a MacOS application, but if you know a Windows one please tell me as well.


texts:
I would like to interface an ADC (in particular this one: http://www.linear.com/product/LTC1400) with an Arduino Nano via SPI. The specified max clock speed for the ADC is 6.4 MHz. The Nano can do up to 8 MHz clock speed, but I'm not able to set 6.4 MHz. If I try this

SPI.beginTransaction(SPISettings(6400000, MSBFIRST, SPI_MODE0));

I get 4 MHz at the clock pin, which means the achievable acquisition rate of the ADC is reduced. Is there a way to get the 6.4 MHz going for maximum acquisition rate with the ADC? Or is there a different approach to get fast data transfer with the ADC (e.g. external clock)?


texts:
Hello everyone i got 2 ssr's from here

(link)

Sorry about the long link. My question is what power supply should i use. I was thinking a 12v 2amp. On a side note do i look at the input or the output when choosing a power supply

Thank you


texts: How to get the MAC address of an Ethernet shield, if it is not printed on it?

texts: Help me to find out how to connect an Ethernet shield over the internet using a LAN cable. I have tried many times but I'm not getting a MAC and IP address.


texts: nrf24l01 (8pin) + adapter board (10pin) oops?

texts:
I just got my first arduino boards and have been learning the basics (so I know very little). I got the 2.4GHz NRF24L01+ (this one: NRF24L01+) and along with it a breakout board (this one: NRF24L01+ board) which I didn't realize was 10pin (nor that there is an 8pin version) vs the wireless board's 8pin. So my question is, is it safe to connect the module to this adapter board in some way? From the pinout of both I would assume not, since for example the bottom two pins on the board are ground (and therefore connected together) and the ground pin on the NRF24L01+ is next to the VCC (NRF24L01+ pinout) and the top two on the board are both VCC 3.3 and from what I can tell by looking at the etched lines, it seems it leads to the resistors (not sure if they are resistors or what, like I said, I know very little still). There seems to be an LED on this board as well, connected to the AMS1117 chip (that's a voltage regulator, correct?).

So, I am guessing I cannot just connect the NRF24L01+ to the adapter board straight in, right? But, can it with some wires? Would that even make sense? Also, is this board even necessary for anything? I bought it having read something somewhere (been reading too much to keep track of where exactly) that recommended it, but a tutorial I saw today didn't make use of it, instead just soldering a capacitor to two of the pins saying some other place recommended it to reduce noise.


texts: Which components to built remapping keyboard via USB in + out (remapped)

texts:
I know that it's fairly easy to change the emulate keyboard and mouse by Arduino. But I'm quite specific about the goal I would like to achieve hence I would appreciate if you could advise me which components (Arduino compatible) I am going to need to have such a built:

Physical usb keyboard --> Arduino via usb IN --> keys remapping (for example pressing q will return ctrl+3 or more advanced action) --> Arduino USB OUT (which I can directly plug in to my computer and receive modified keyboard commands).

To sum up I  just want Arduino to work as intermediary.

Will simple Arduino Uno + USB shield do the work?

Thank you a lot for your support!


texts:
I've got an Arduino mega compatible board, called Ethermega, from Freetronics (ATmega2560).
Schematic here.
In setup, I've written this code:
Serial.begin(9600);
  pinMode(4, INPUT_PULLUP);
  digitalWrite(4, HIGH); // Optional, I tried with and without
  while (1)
  {
    if (digitalRead(4) == HIGH)
    {
      Serial.write("Up!\n");
    }
  }

(Don't worry about the fact I'm not using loop)
When I connect input 4 with 5V, I see "Up!". Rest of the time, I see nothing.
Considering I have enabled the internal pull-up, I'm expecting it should be up/high by default, and I would have to connect it to GND to get it low...
Another thing that puzzles me is I can find heaps of examples that use a tactile switch and no pullup/pulldown at all...
So what am I missing or doing wrong? Seems like whatever I do, I've got some kind of pulldown enabled...


texts: Can an ultrasonic sensor differentiate b/w objects?

texts:
Can we potentially use an ultrasonic sensor to differentiate between objects based on the reflective capacity of the object?
For example to differentiate between metals and biodegradable wastes.


texts:
just a quick question on an oddity I noticed while playing with serial on my Arduino.

I'm using the serial monitor to test an interface I plan to adapt to Bluetooth later. Except I'm noticing if I only read fixed sizes with readBytes I can only ever input data of that exact byte length or my serial connection gets broken.

Example pseudocode:

Serial.write(Serial.available());
if(Serial.available() >= NUM_BYTES){
  Serial.readBytes(buffer,NUM_BYTES);
/* Do stuff */
}

If I input something of length NUM_BYTES + 1, it reads the first NUM_BYTES. But then I can never send more data over the serial monitor. Why is this? Is it part of the serial implementation? (The write would always be 1 afterwards even if I try to send more.)

A fix I had was just to clear the buffer by calling Serial.read() until nothing else was available. As a matter of curiosity too... If anyone cares to answer or give me a link to some reading - is there a way to check before I write to serial to make sure there's buffer space for my message on an Arduino? I read that they have a 64 byte buffer for data but I'm unsure how the protocol caters to sending larger sets of data if the buffer ever overflowed. Perhaps the serial library is using some form of ack behind the scenes?


texts: Display unresponsive in one sketch, while working in another

texts:
I'm using a DOGM163 Display. It works in a DEMO sketch provided by the manufacturer but not in my sketch. This is strange, because I am using the same library specific commands as in the example.

I think of the following possibilities:

Something inside the other libraries I use in my sketch is hindering the dogm from working (perhaps by fiddling around with the ports connected to the display).
I've got a power problem which surfaces when doing more than just that demo.
Timing is botched.
Something with my wiring is wrong. Perhaps in conjunction with 1).

I'm using:

#include <Arduino.h>
#include "newsched.h"
#include "dplan.h"
#include <EEPROM.h>
#include <PinChangeInt.h>
#include <dogm_7036.h>
#include <SPI.h>
#include <OneWire.h>
#include "lampcontrol.h"

Power seems to be ok, as I'm receiving all debug messages via serial correctly.

The display is sharing its port with a port expander and a SD-port. But removing the SD-port doesn't change the problem.

Update (Part1)
Here comes the code, which works:

http://pastebin.com/eXUVzeV8

This is a slightly modified manufacturer example. But it does what it should do. It displays the demo text.

Here comes, what doesn't work:

Main sketch
newsched.h
newsched.cpp
display.h
display.cpp
menu.h
menu.cpp

The other source files, 19 in total!, can be posted on request, but as you can see from newsched.cpp I already disabled most of the code to narrow down the error.

What exactly means "not work"? Not work means, the display seems to be turned off. The LED backlight is on, but you cannot see the grey character boxes (due to display bias), which appear in the working code sample.

Update 2
Schematic:


texts: C# Arduino: How to detect if the needed software is present on the computer

texts:
I have a digispark that uses trinket keyboard library to send media keys back to the computer using a rotary encoder. I currently have it configured to send normal media keys but about 2 weeks ago i started needing to change binds on what the rotary encoder does so i needed a driver of some sort. i asked and i got answers that i can't use serial ports but i can use unused keys like f13+ keys so i use the f keys now to communicate to c# software (it listens on these f keys and as soon as they are pressed depending on the configuration it does what it needs to do).
I don't think that code is needed for this demonstration but if u need it i'll be happy to edit this.

So i made the software and now comes a problem of what happens when u plug in the device that doesn't have the driver. its useless, so i need a way for the digispark to find out if there is a software that can "reprogram" what the rotary encoder does and if there isn't use the default functions(the media keys).

Questions:

How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in
Is there any way to add my program made in c# to the digispark, i got a usb headset and when i first plugged it in it installed its driver, so when i plug in my digispark can it load the program

Solutions that i think may work but i have no idea how to do them:

using one of these unused keys as Boolean, when its held down lets say by the c# software can the digispark using the trinket or any other compatible Tiny85 library determine if that key is pressed down or not (this may interfere with other software so i don't think its perfect solution)
If anyone here knows any library or custom firmware that allows the digispark(Tiny85) to communicate on serial ports that'd be pretty useful and would solve the whole question.

For the second problem: do i need any other hardware to do this as i only have a Tiny85 digispark and a rotary encoder with a breakout board

If you have a solution please provide me code or links where i may learn how to do this because as of now i have no idea how to do this, i know my way around c# but i'm a noob in arduino programming. I already asked this on stack overflow a week ago but didn't get any comments or answers. I'm sorry if this counts as a duplicate i'll remove the one on stack overflow if needed. thank you for understanding


texts:
I have Googled quite a lot regarding using a C++ program for uploading to Arduino and related, however I am confused now. Right, my problem is this:

I have written a C++ program which imports RGB data of a 24 bit bitmap (which was generated using Matlab) and now I would like to use this array (3 arrays - R,G,B) for an Arduino sketch to be used for a LED matrix project that I am working on. I am not exactly a programmer and hence had to resort to this path -- MATLAB to c++ and then Arduino, although this could be entirely done in C++ too (importing a bitmap and extracting pixel info). So, my C++ code spits out the 3 arrays and I am not sure how to get those into an Arduino sketch.

I read a lot about this and I understood this - As the Arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++? I cannot understand much of this method, hence trying to bypass this.

If anybody's got any better method, I would be really glad if you could share it. I am also looking to use the Arduino package for MATLAB to send the array directly from there using serial communication. But I just wanted to make sure I at least tried this path.

Would really appreciate if somebody could offer some help. I am quite stuck here.

Can share any other info if required.

Thanks a lot!

EDIT 1:

To clarify as Nick Gammon pointed out in the comments below. In brief steps, this is what I have done till now:

Got a 24 bit bitmap (some random image)
Extracted the RGB data for each pixel using Matlab
Have 3 arrays of (for eg.) 122X300 dimensions whose every element has values between 0-255 (8 bit) and for R,G and B colors
Want to get these 3 arrays for use in Arduino sketch for further working
Stuck here - how to do that .....
So I did this - I imported that the RGB data into 3 separate text files and made a c++ program to read those arrays assuming that I should be able to then somehow use this program in Arduino sketch.
Now I am not sure what to do....my goal would be to have these 3 arrays (CRGB arrays, FastLED) in my arduino sketch which I can control and then upload to my Due.
On googling I found that to use c++ for arduino , you need the avr compiler and make file, which I want to avoid. Tried other IDEs too, Eclipse, PlatformIO too .. ummmm ... not that successful to be honest.
as per Paul's ans- Matlab to Arduino method I have to try.
Hope I have clarified my process till now :)

EDIT 2:

C++ code for reading the above array (thought I could use the output in Arduino)

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <sstream>
#include <stdlib.h>

const int HEIGHT = 4;

const int WIDTH = 5;

using namespace std;

int main(){

  int array_req [HEIGHT][WIDTH];

string userinputprompt, filename;

userinputprompt = "COLORDATA FILENAME: ";

cout<<userinputprompt<<endl;

getline(cin,filename);

ifstream inputfile;

inputfile.open(filename.c_str());

 for (int i = 0; i < HEIGHT; ++i)
{
  std::string tmpString;
  std::getline(inputfile, tmpString);

 std::stringstream ss(tmpString);

 for(int j=0;j < WIDTH; ++j)
  {
    ss >> array_req[i][j];
  }
 }

    for(int p=0; p<HEIGHT; p++)
    {
      for(int q=0; q<WIDTH; q++)
    {
        cout<<array_req[p][q]<<" ";
    }
    cout<<"\n";
}

inputfile.close();
getchar();
return 0;

}


texts:
Can anyone assist me with read/write to a SD shield. I am using a arduino along with a SD shield (POD  uSD) I am using a ultrasonic sensor to measure a distance, it has a safety factor in it. It also measures the time a measurement was taken, I now need to save the data from the serial monitor to a file and send that file to a SD card. I cannot seem to solve the saving a file part along with the SD shield

I have wrote my code but can seem to implement the shield along with my code, I want to store my data onto a file on the SD card. I've reviewed the example provided in the library's but it won't work for me

My code is;

#define redled 10
#define greenled 11
#define echoPin 12
#define trigPin 13

unsigned long interval=60000; //interval = 60 seconds
unsigned long previoustime=0;
int minutes = 0; //global variables

void setup() {
  Serial.begin (9600); //Set Baud rate to 9600 to match serial monitor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(greenled, OUTPUT);
  pinMode(redled, OUTPUT);
}

void loop() {
 //-----------------------------------------------------------
  unsigned long currenttime = millis(); //counts time in milliseconds and puts it into current time
  if ((currenttime-previoustime) >= interval) { //When time is greater 60 seconds
    previoustime = currenttime; //Make the previous time equalled to the minute to take away in the next if statement        **Time since start section**
    minutes = minutes + 1; //Add 1 minute
  }
  unsigned long time = (currenttime-previoustime) / 1000; //converts the milliseconds to seconds
  //-----------------------------------------------------------
  long distance = ultra_sensor(); //call function that now returns the distance
  //-----------------------------------------------------------
  if (distance < 4) {            // If distance is less than 4cm
    digitalWrite(redled,HIGH);   // Turn on Red LED
    digitalWrite(greenled,LOW);  // Turn off Green LED
  }
  else {                          //If distance is greater than 4cm
    digitalWrite(redled,LOW);     // Turn off Red LED
    digitalWrite(greenled,HIGH);  // Turn on Green LED
  }
  //-----------------------------------------------------------
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.print("cm");
    Serial.print(" after ");
    Serial.print(minutes);              //Printing distance and time to serial monitor
    Serial.print(" minutes ");
    Serial.print("and ");
    Serial.print(time);
    Serial.println(" seconds");
  }
  //-----------------------------------------------------------
  delay(2000); //Get reading every 2 seconds
}

long ultra_sensor() { //Ultrasonic sensor reading is now a function. More efficient
  digitalWrite(trigPin, LOW);  //Set Trigger to idle
  delayMicroseconds(2); //Wait 2 microseconds
  digitalWrite(trigPin, HIGH); //Set Trigger to high which sends out a wave
  delayMicroseconds(10); //Send the wave for 10 microseconds
  digitalWrite(trigPin, LOW); //Turn the trigger to idle
  long duration = pulseIn(echoPin, HIGH); //make duration the wave that echo recieves back
  long dis = (duration/2) / 29.1; //divide by 2 for going there and back.                         ***Speed of sound***
  return dis; //Send the distance to function call
}


texts:
I got a Sparkfun Redbot Kit a while back. I ended up building it vanilla and it was a good introduction to the board (the board is basically Uno and a motor shield in one) and the toys that came with it. I figured if could scavenge an RC car, I'd get a more robust redbot. I found an old RC Rock Crawler, it has a basic suspension, two motors, and a steering servo.
Unfortunately, I encountered a problem. The steering servo only has two wires. I loaded the Servo -> Sweep example that is default in the Arduino IDE to see if I could make it work regardless. I tried all the different all the different wire/header combinations on the servo headers:

When I attach the wires to gnd and # I get a buzzing noise.
When I attach the wires to gnd and pow the servo turns left or, if I swap the wires, it turns right.
When I attach the wires to pow and # nothing happens.

I currently can't take advantage of the servo headers on the board (or at least I don't know how to). I was hoping that I could that there might be a work around, I just don't know what it is.
The obvious answer is that I could run both motors off of only one of the headers and use the other to control the steering (thats how the original board from the car was wired), but I can get a faster car if each motor has its own header, and I'm all about the vroom vroom...

I'm running the whole thing off the default 6v (4 AA) battery pack. I might be able to wire in the extra 2 AA's for the extra 3v but I don't want mess with the wiring on the pack unless I know it's going to work.

I have an accelerometer connected to the A4 A5 header block and the motors connected too (I checked w/o them connected but there was no difference).

Image courtesy of https://learn.sparkfun.com/tutorials/getting-started-with-the-redbot
More info on the redbot board https://www.sparkfun.com/products/12097


texts: How do I use two PulseIn() functions simultaneously in Arduino?

texts: I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?


texts: Can I extend esp32 bluetooth range with wifi antenna

texts:
My Arduino ESP32 D1 R32 only has a Bluetooth range of about 2-3m and the signal can't pass through any obstacles. Will fitting a wifi antenna to it like this
extend my Bluetooth range and create a more powerful signal or will it just cause interference from the signal bouncing off walls? I would like a range of about 5m.


texts: if I solder the jumper pads on the adafruit cc3000 for use with the Arduino Mega will it still work fine with the Uno?


texts: Why my Galileo isn't getting a IP address?

texts:
I have an Ethernet cable connected to my router. I connected the other end to my laptop and got a successful connection. When I plug it into my Arduino Galileo gen2, even with Ethernet port green light on, I got nothing when I run this:

delay(1000);
system("ifconfig eth0 > /dev/ttyGS0");

This is my output:

eth0      Link encap:Ethernet  HWaddr 00:00:00:00:00:00
      BROADCAST MULTICAST  MTU:1500  Metric:1
      RX packets:0 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
      Interrupt:41 Base address:0x8000

What I'm doing wrong?


texts: Receiving half the value of Reference Voltage in AD7705?

texts:
I have a doubt in the AD7705 library AD7705 Library Link when I am declaring a reference voltage of 5 V and giving a reference voltage of 5 V to IN1+. On the serial monitor, I can see ADC conversion from 2.5V to 5 V when I vary the potentiometer.
whatever reference voltage I am giving it is divided by 2.
What parameter should I change to get full-scale voltage reading?
Thanks in Advance!


texts: Unable to add multiple potentiometer in Midi controller

texts:
I am building a simple arduino based midi controller to send cc midi messages. However I am able to send messages only through A0 (analog input).. Any help on this will be appreciated,..

    #include <MIDI.h>
int pot[] = {A0,A1,A2};
int AnaPinsNum = 3;
int potIn[] = {0,0,0};
int analogValue = 0;

int lastAnalogValue[] = {0,0,0};

 void setup()
 {
  MIDI.begin(4);
  // 115200 hairless MIDI
  Serial.begin(115200);
  int i;
  for (i = 0; i < 3; i++);
 }
 void loop() {

  int i;
  for (i = 0; i < AnaPinsNum; i++)

  potIn[i] = analogRead(pot[i])/8;

  // potentiometer could be too sensitive and
  // give different (+-1) values.
  // send CC only when the difference between last value
  // is more than 1
  if ((potIn[i]-lastAnalogValue[i]) > 1 || (potIn[i]-lastAnalogValue[i]) < -1) {
    // value changed?
    if (potIn[i] != lastAnalogValue[i]) {
      // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      MIDI.sendControlChange(1, potIn[i], 1);
      lastAnalogValue[i] = potIn[i];
    }
  }

}


texts:
x = 5;
Serial.println (x);

if (x == 0);
    {
      //stuff in this IF keeps happening why ?
      //Iam too stupid ?
    }


texts: Arduino RBBB - Device not accepting address

texts:
I recently purchases and make a Arduino RBBB with a BUB II from Modern Device. I ordered the package found HERE. I built everything according to the instructions, but when I connect it to my laptop (running Ubuntu 14.10), I get the following in dmesg

[63415.213391] usb 3-1: new full-speed USB device number 63 using xhci_hcd
[63415.381403] usb 3-1: device descriptor read/64, error -71
[63415.485225] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 26.
[63415.485240] usb 3-1: hub failed to enable device, error -22
[63415.597236] usb 3-1: new full-speed USB device number 64 using xhci_hcd
[63415.709154] usb 3-1: device descriptor read/64, error -71
[63415.813102] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 27.
[63415.813116] usb 3-1: hub failed to enable device, error -22
[63415.925108] usb 3-1: new full-speed USB device number 65 using xhci_hcd
[63415.925270] usb 3-1: Device not responding to setup address.
[63416.129120] usb 3-1: Device not responding to setup address.
[63416.332902] usb 3-1: device not accepting address 65, error -71
[63416.444973] usb 3-1: new full-speed USB device number 66 using xhci_hcd
[63416.445174] usb 3-1: Device not responding to setup address.
[63416.649008] usb 3-1: Device not responding to setup address.
[63416.852734] usb 3-1: device not accepting address 66, error -71
[63416.852813] usb usb3-port1: unable to enumerate USB device

It is repeatable every time I insert. lsusb does not register it. I have read that I should switch out the cable, but it is brand new (and I don't have another to test with. I was wondering if there is something evidently wrong with my circuitry. I posted pictures


texts:
I am having a problem with a MAXIM Serial module (Config A) with a simple repeating code from COM port. When sending a character (k:0x6b) I receive a (0x00) echo.

Without the module and just connecting the arduinos crossing the TX/RX cables, I do not have any echo.

The echo persists, disregarding of:

The speed (from 38400 to 2000000 bps),
Using or not the high speed options (2.3MOhm for 250000bps) of the MAXIM,
Using or not 120 ohm terminal resistors,
Both grounds are 0V, connecting them has no effect,
Removing the A (red) B (green) Serial Bus Cables (???). Message not send in this case, as expected (!).

What could be the problem?

Devices:

Two Arduino Mega 2560,
Two MAX3292, one for each arduino,
AWG24 Cable, shorter than 7 in each.

Config A: With Module (00 echo), Half Duplex (f.19 p.13).

Config B: Without Module (No echo), only crossed cables

Code:

long rate=38400;
void setup() {
    Serial.begin(rate); while (!Serial);
    Serial1.begin(rate); while (!Serial1);
    pinMode(22,OUTPUT);
    pinMode(23,OUTPUT);
}
char s;
void loop() {
    if (Serial.available()) {
        digitalWrite(22,1);
        digitalWrite(23,1);
        s=Serial.read();
        Serial1.write(s);
        Serial1.flush();
        digitalWrite(23,0);
        digitalWrite(22,0);
    }
    if (Serial1.available()){
        s=Serial1.read();
        Serial.write(s);
    }
}

Execution: Four k sent, 0x00 echoes received. After this, four k send from other arduino, received successfully.

Epilogue.

Actually, the problem was a resistor at the RO output, not shown in the diagram ("The problem is in the code you didn't post").

It was a voltage divider for a 5V3.3 conversion in the Arduino Due case, useless in the Arduino Mega, but still there.

Theorizing a reason, that resistor caused a spike at the output (?), thus forcing the module to interpret it as another byte, an empty one (?).

After removing the resistors, it worked perfectly.
Now I migrated this back into Arduino Due, but with a diode plus a pull up resistor as a 5V3.3 converter.


texts:
I have this HLK-RM04:

It came with  no catalogue or manual
all threads about it are in Chinese
after when I found the configuration webpage and changing it to client
it wont connect and it stopped board casting hlink wifi
how could i reset to factory settings?

After very long search I found an English manual.

What does Trst means ?
I don’t understand what I must do to reset it!


texts:
I made a circuit which in my intentions would allow me to toggle a LED dimming loop.

Problem is that once I push the button the first time pushing it a second time doesn't toggle the LED loop off.

Here is the code:

const int LED = 9; // the pin for the LED
const int BUTTON = 7;

int val = LOW;

int old_val = LOW;
int state = 0;
int i = 0;

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT);

}

void loop()
{
  val = digitalRead(BUTTON);

  if ((val == HIGH) && (old_val==LOW))
  {
    state = 1 - state;
    delay(10);
  }

  old_val = val;

  if (state == 1)
  {
    for (i = 0; i < 255; i++)  // loop from 0 to 254 (fade in)
    {
      analogWrite(LED, i); // set the LED brightness
      delay(10);           // Wait 10ms because analogWrite
      // is instantaneous and we would
      // not see any change
    }

    for (i = 255; i > 0; i--) // loop from 255 to 1 (fade out)
    {
      analogWrite(LED, i); // set the LED brightness
      delay(10);           // Wait 10ms
    }
  } else
  {
    analogWrite(LED, 0);
  }

  if ((val == LOW) && (old_val == HIGH))
  {
    delay(10);
  }
}

Here is the circuit scheme:

I would be interested both in learning what the problem is AND learning any mental methods I can apply to debug in such situations.


texts: Is Arduino stable enough to use it for a door lock?

texts:
I want to replace my door lock with an one made with an Arduino and a servo, but I'm not sure if the platform is stable enough to use it for something like this.

If I do everything right (code, connections, constant power), could I trust in this?


texts: nrf24l01+ does not work with a battery, or very unreliably

texts:
For a project in progress, I have an Arduino UNO sending a message when a condition occurs, and a Raspberry Pi that listens to it. Both are fitted with NRF24L01+ modules with antennas.

It works perfectly when the Arduino is powered from a wall socket, for instance using a 9V / 1A power supply. But when I try it with a 9V battery (which is supposed to supply 600 mAh), the Raspberry Pi receives only 1/10 of the messages.

Could you tell me:

Why this happens
How I can solve this problem (software / wiring / capacitor / ...)
What would be the best way to power an Arduino whose only job is to detect that a switch closes, and emit a message over the air

Here is the code of the emitter (Arduino). And there is the code of the receiver (Raspberry Pi).

Thank you.


texts:
I am new to the Arduino platform so please bear with me. I have a program to display rolling text on a LED matrix which is for the Tinyduino platform

#include "Charliplexing.h"
#include "Font.h"
#include "Arduino.h"

void setup()
{
  LedSign::Init();
}

static char test[]="HELLO";

void loop()
{
  for (int8_t x=DISPLAY_COLS, i=0;; x--) {
    LedSign::Clear();
    for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
      int8_t w = Font::Draw(test[i2], x2, 0);
      x2 += w, i2 = (i2+1)%strlen(test);
      if (x2 <= 0)  // off the display completely?
        x = x2, i = i2;
    }
    delay(80);
  }
}

Then I have some code to read temperature and humidity data for the same Tinyduino platform

#include <Wire.h>
#include <SI7021.h>

SI7021 sensor;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.print("Initializing sensor... ");
  if(!sensor.begin()){
    Serial.println("Sensor not found!");
    while(true);
  }
  Serial.println("Success!");
}

void loop()
{
  int celcius=sensor.getCelsiusHundredths()/100;
  int relativeHumidity=sensor.getHumidityPercent();
  Serial.print(celcius);
  Serial.print(" deg Celsius\t");
  Serial.print(relativeHumidity);
  Serial.println("% relative humidity");

  delay(500);
}

I am trying to integrate this together so that Arduino reads the temperature and humidity sensor data and then displays it on the LED matrix as text. I have some code that is integrated from the above two examples

#include "Charliplexing.h"
#include "Font.h"
#include "Arduino.h"
#include <Wire.h>
#include <SI7021.h>

SI7021 sensor;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.print("Initializing sensor... ");
  if(!sensor.begin()){
    Serial.println("Sensor not found!");
    while(true);
  }
  Serial.println("Success!");
  LedSign::Init();
}

static char test[100]="";

void loop()
{
  int celcius=sensor.getCelsiusHundredths()/100;
  int relativeHumidity=sensor.getHumidityPercent();
  test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

  for (int8_t x=DISPLAY_COLS, i=0;; x--) {
    LedSign::Clear();
    for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
      int8_t w = Font::Draw(test[i2], x2, 0);
      x2 += w, i2 = (i2+1)%strlen(test);
      if (x2 <= 0)  // off the display completely?
        x = x2, i = i2;
    }
    delay(80);
  }
  delay(500);
}

Here is the error message that the IDE throws out

test:28: error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

 test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";
                             ^

Using library LOL in folder: C:\Program Files (x86)\Arduino\libraries\LOL (legacy)
Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
Using library Temp in folder: C:\Program Files (x86)\Arduino\libraries\Temp (legacy)
exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Any suggestions on how to resolve this error is welcome.


texts: MCU to switch single coil latching relay not working (attempting array with common gnd)

texts:
I have several single coil latching relays, (EC2-5SNU).

I am trying to control them by an MCU; connected directly they work fine, but I am iffy about keeping it this way so I'm trying to power them through a darlington pair array, (ULN2003).

Using the non-latching type, these work fine through the ULN2003, but attempting to interface the code below with the latching type isn't going so well and i can't figure out why:

int right = 12;
int left = 10;

void setup() {
  pinMode(right, OUTPUT);
  pinMode(left, OUTPUT);
}

void loop() {
  digitalWrite(right, HIGH);  //reset
  digitalWrite(left, LOW);
  delay(2000);
  digitalWrite(right, LOW); //set
  digitalWrite(left, HIGH);
  delay(2000);
}

I have four connected with a common pin, but to simplify i've tried and failed to have the code above work on a single relay, as shown below:

Measuring the voltages out of the MCU show the correct levels, keeping in mind the ULN2003 acts an inverter, so i've set the boolean logic accordingly.

The voltages at the output of the ULN seem to stick at 0.6V, I've tried a bunch of permutations, including having one pin (on the common pin setup) connected directly to the MCU.

Does anyone have any ideas?


texts: Programing a Mini 05 without a USB-to-serial converter

texts:
I have an Arduino Mini 05 clone Wattuino, an Elegoo Mega, a Powerboost 1000c, but not access to a USB-to-serial converter. Is there any way to program the Arduino Mini with these devices?

I tried to search it but they only mention using an Arduino uno as the chip can be put out of the board. Discusion


texts: How to send an integer through pyserial with Python to an Arduino and get back the same result?

texts:
There has been similar questions all over the internet but none of them seem to answer my question, so can anybody tell me what is wrong with this code and how I can fix it?

Python code:

import serial

arduino_linux=serial.Serial("/dev/ttyACM0",9600)
while True:
    print('write:',str.encode('90')) #print the sent value through the serial to check it with the readed value
    arduino_linux.write(str.encode('90'))#send the following value
    print('readed:',arduino_linux.read())#read the same value back from the arduino

my arduino code is as follows

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

}

void loop() {
  Serial.write(Serial.read());

}

this is a simple sample of a project, my aim from this code is to send the integer number 90 from the pyserial and make sure the value the Arduino is reading is the same integer.

In case if necessary my project is an object follower with object detector and after calculating all the angles and everything it sends them to the Arduino so the Arduino can act up on the servo's.

This is the result I am getting:

But I would like something like:

write:b '90'

readed:b '90', not b'9' or b'0'

I would also like to know how I can change these bytes to integers before I write them to a servo.


texts: Can a PC connect to an Arduino for serial communication without installing the entire dev kit?

texts:
I'd like to send a prototype board to a friend pre-programmed and wired. Ideally they should just need to plug in the USB and connect to it over a serial COM port.

With another laptop I used for testing I had to install the full dev kit, sketch editor and all to get it working.

Can I somehow send just the portion of the kit that provides the COM drivers and not the rest? Is there a prebuilt install for just that portion?


texts: How to upload an arduino sketch from java / processing?

texts:
I'm trying to upload a hex file from Java/Processing but running into some issues.
Here is my code so far, based on the Arduino IDE's upload verbose output:

void setup(){
    //C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM96 -b115200 -D -Uflash:w:C:\Users\HM\AppData\Local\Temp\build5909267154049588263.tmp/sketch_aug13a.cpp.hex:i
    String ArduinoPath = "C:\\Program Files (x86)\\Arduino";
    String hexPath = "C:\\Users\\HM\\AppData\\Local\\Temp\\build1023547366107161384.tmp/sketch_aug13a.cpp.hex";
    String port = "COM96";
    runCommand(new String[]{ArduinoPath+"/hardware/tools/avr/bin/avrdude", "-C"+ArduinoPath+"/hardware/tools/avr/etc/avrdude.conf","-v","-v","-v","-v","-patmega328p","-carduino","-P"+port,"-b115200","-D","-Uflash:w:"+hexPath+":i"});
  }
  void runCommand(String[] cmd){

    String s = null;

    try {

      Process p = Runtime.getRuntime().exec(cmd);
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
      BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

      // read the output from the command
      System.out.println("command out:\n");
      while ( (s = stdInput.readLine ()) != null) System.out.println(s);
      System.out.println("errors (if any):\n");
      while ( (s = stdError.readLine ()) != null) System.out.println(s);

    }catch (IOException e) {
      System.out.println("something went wrong: \n");
      e.printStackTrace();
    }

  }

If I run this from command line it uploads without any issues, but from the code above I always get this output:

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardw
are\tools\avr\etc\avrdude.conf"

         Using Port                    : COM96
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM96": Access is denied.

avrdude done.  Thank you.


texts:
I'm struggling with get suitable step delay while driving a stepper motor.

How to calculate exact step delay for 1.8deg/step stepper motor?
Give some example calculation.


texts: Choose the control threshold using the up and down buttons in 0.1 increments / decrements

texts:
I need to add 2 buttons, One that increases the threshold and One that decreases the threshold once u changed It the led gonna turn up at another value.
My Code:
#include <LiquidCrystal.h>

#define analogInput 0

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

    float vout = 0.0;

    float vin = 0.0;

     float R1 = 100000.0;

    int value = 0;

void setup(){

   lcd.begin(16, 2);

   lcd.print("VOLTMETRO DC");

   Serial.begin(9600);

   pinMode(6, OUTPUT);

}

void loop(){

   value = analogRead(analogInput);

   vout = (value * 5.0) / 1024.0;

   // inserire al posto di 5.0V l`uscita in volt tra i Pin 5V e GND di Arduino

lcd.setCursor(0, 1);

lcd.print(" ");

lcd.setCursor(0, 1);

lcd.print("INPUT V= ");

lcd.print(vout);

if(vout > 2.5)

{

  digitalWrite(6,HIGH);

  lcd.setCursor(15, 0);

  lcd.blink();

}

else

{

  digitalWrite(6,LOW);

  lcd.setCursor(15, 0);

  lcd.noBlink();

}

delay(500);

}

My circuit:
https://ibb.co/85rx3gf


texts:
I currently know 3 ways to do a program. Which one of them is the most memory friendly. Note that the example code is simple (blinking a led) and the final code will be VERY VERY complex. Also, the way I code is not the best, so suggest any suggestions in the way to write things or where to put them please.

1- All in the loop. The most basic way of programming.

const int led = 2;
const int interval = 500;
bool ledState = false;

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

void loop() {
  ledState = !ledState;
  digitalWrite(led, ledState);
  delay(interval);
}

2- Functions. Similar to the loop but a little neither. Can be splitted into many tabs.

const int led = 2;
const int interval = 500;
bool ledState = false;

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

void loop() {
  blinkLed();
}

void blinkLed()
{
  ledState = !ledState;
  digitalWrite(led, ledState);
  delay(interval);
}

Then finnaly, objects. The most supreme of them all (and the one that I know the least). I like objects and classes because multitasking with it is much easier. It is more flexible too. Code taken from here.

class Flasher
{
  // Class Member Variables
  // These are initialized at startup
  int ledPin;      // the number of the LED pin
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int ledState;                 // ledState used to set the LED
  unsigned long previousMillis;   // will store last time LED was updated

  // Constructor - creates a Flasher
  // and initializes the member variables and state
  public:
  Flasher(int pin, long on, long off)
  {
  ledPin = pin;
  pinMode(ledPin, OUTPUT);

  OnTime = on;
  OffTime = off;

  ledState = LOW;
  previousMillis = 0;
  }

  void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(ledPin, ledState);   // Update the actual LED
    }
  }
};

Flasher led(2, 500, 500);

void setup()
{
}

void loop()
{
  led.Update();
}

So, which is the best out of those 3.


texts: Atmega328 xbee and softaware serial libraries

texts: I use an atmega328 with fdti cable wired at rx/tx and i want to connect a zigbee s2 at diferrent pins. I have tried to use  SoftwareSerial library but i would like to use the xbee library too. Is there a way to use both libraries? If there is no way doing this, is it a problem to connect both fdti cable and zigbee at the same rx/tx? In the future, in opposition to fdti cable i will use a micro usb avr.


texts: Set and extract individual bytes of a number (lowByte() and highByte())

texts:
You can extract

  the low-order (rightmost) byte of a variable

or

  the high-order (leftmost) byte of a word

with the functions lowByte() and highByte() respectively (the quotes are from the Arduino Reference).

Does Arduino provide a way to extract any byte from a number with a similar function?

And does it provide a way to set any individual bytes of a number (which would be the counterparts to these functions, if they exist)?


texts:
I have an project which control a heat exchanger.

I read 4 temperature sensors DS18B20, a distance with HC-SR04 Ultrasonic Sensor, and a flow with YF-S201 (with attach interrupt). I can turn on and off a monophasic motor with Arduino too.

I have many interference problems with i turn on my motor, the readings of temperature fail with big frequence and i have many errors with interrupt counter.

I read many posts about interferences, and one most important factors are high impedance of floatings pins.

I use Arduino Due, then many pins are floating. I have to put a pull-down resistors in all pins?

My project looks like the architeture in the image link bellow:
https://i.stack.imgur.com/glo5L.jpg

The code of my project can be found in :
https://github.com/felipefonsecabh/ArduinoCode/blob/ArduinoNoNavigation/ArduinoCode.ino

Any opinion?


texts: Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.”

texts:
I am having Issue while connecting ESP8266 with Arduino Mega. It always says "Module have no response."

Please check and correct me if I am wrong anywhere.

I am using below code and and wiring diagram is

My Code:

//#include <SoftwareSerial.h>
   //use mega Serial 2 for serial monitor; Serial 1 on pins 19 (RX) and 18 (TX);// Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
   #define SSID "SopraSteria"
   #define PASS "1234567890"
   #define DST_IP "220.181.111.85" //baidu.com
   //SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     //serial 2 is to esp8266
     Serial2.begin(115200);//9600 (mine), 57600, 115200
     Serial2.setTimeout(2000);

     //serial 0 is to usb
     Serial.begin(115200);

     while(!Serial);
     while(!Serial2);

     //dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     //dbgSerial.println("ESP8266 Demo");
     Serial.println("ESP8266 Demo on Mega2560");

    while(Serial2.available()>0)
    Serial2.read();

     delay(1000);
       //test if the module is ready
     Serial2.println("AT+RST");
     //delay(1000);
     //delay(1000);
     Serial.println("Resetting module");
     Serial2.flush();
     //Serial.println(Serial2.read());
     //if(Serial2.find("ready"))
     if(Serial2.find("Ready")||Serial2.find("ready"))
     {
       //dbgSerial.println("Module is ready");
       Serial.println("Module is ready");
     }
     else
     {
       //dbgSerial.println("Module have no response.");
       Serial.println("Module have no response.");
       //while(1);
     }
     delay(1000);
     //connect to the wifi
     boolean connected=false;
     for(int i=0;i<5;i++)
     {
       if(connectWiFi())
       {
         connected = true;
         break;
       }
     }
     if (!connected){
      //while(1);
      Serial.println("Not Connected.");
     }
     delay(1000);
     //print the ip addr

   Serial2.println("AT+CIFSR");
     Serial.println("ip address:");
     while (Serial2.available())
     Serial.write(Serial2.read());

     //set the single connection mode
     Serial2.println("AT+CIPMUX=0");
   }
   void loop()
   {
    //connectWiFi();
     String cmd = "AT+CIPSTART=\"TCP\",\"";
     cmd += DST_IP;
     cmd += "\",80";
     Serial2.println(cmd);
     Serial.println(cmd);
     Serial.println(cmd);
     if(Serial2.find("Error")) return;
     cmd = "GET / HTTP/1.0\r\n\r\n";
     Serial2.print("AT+CIPSEND=");
     Serial2.println(cmd.length());
     if(Serial2.find(">"))
     {
       //dbgSerial.print(">");
       Serial.print(">");
       }else
       {
         Serial2.println("AT+CIPCLOSE");
         //dbgSerial.println("connect timeout");
         Serial.println("connect timeout");
         delay(1000);
         return;
       }
       Serial2.print(cmd);
       delay(2000);
       //Serial.find("+IPD");
       while (Serial2.available())
       {
         char c = Serial2.read();
         //dbgSerial.write(c);
         Serial.write(c);
         //if(c=='\r') dbgSerial.print('\n');
         if(c=='\r') Serial.print('\n');
       }
       //dbgSerial.println("====");
       Serial.println("====");
       delay(1000);
     }
     boolean connectWiFi()
     {
       Serial2.println("AT+CWMODE=1");
       String cmd="AT+CWJAP=\"";
       cmd+=SSID;
       cmd+="\",\"";
       cmd+=PASS;
       cmd+="\"";
       //dbgSerial.println(cmd);
       Serial2.println(cmd);
       Serial.println(cmd);
       delay(2000);
       if(Serial2.find("OK"))
       {
         //dbgSerial.println("OK, Connected to WiFi.");
         Serial.println("OK, Connected to WiFi.");
         return true;
         }else
         {
           //dbgSerial.println("Can not connect to the WiFi.");
           Serial.println("Can not connect to the WiFi.");
           return false;
         }
       }


texts: connection issues with 3 arduinos any suggestions?

texts:
I have 3 arduinos that I want to program on, all of them with their own cable and I have tried to connect them to my laptop on several different usb ports, my usb ports work with mouses so that's unlikely to be the problem. However I just cannot connect to them they just don't appear under /dev/ttyACM* and the arduino IDE cannot find them either. I'm running ubuntu 14.04 any suggestions for finding out what is likely to be wrong with my system or the arduinos?

For some odd reason they now all appear to be seen as /dev/ttyACM* but they now all give me a

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

error

Anybody have any idea how to fix? The arduino's do not have any wires in them except usb (nothing in reset or any other pin), I'm on ubuntu so the drivers shouldn't be an issue? And pin 13 flashes when I reset the arduino.


texts: 4 consecutive bytes in buffer to unsigned long

texts:
I wonder if there's a smarter way to get these 4 consecutive bytes from a buffer, concatenated in a unsigned long.

// the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, extract the two words:

unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = ");
Serial.println(secsSince1900);

Seems overkill to me, thinking these 4 bytes are already consecutive in the buffer.

Result should be unchanged i.e. having the value in a variable.


texts: In the latest version of Arduino Desktop IDE, are there all features of Arduino Web Editor?

texts:
I would like to know if there are always the latest features in Arduino Desktop IDE if I update it every day.

I mean if there is a new feature in Arduino Web Editor, can I get it on Arduino Desktop IDE?


texts:
I am looking for an Arduino-based solution for an automotive lighting application.

System Requirements:

Able to Operate in Automotive (Interior) Environment (12 +/- 2V DC    Voltage)
Minimum 3 12 V DC Inputs (Preferably 6)
Minimum of 3 12 V DC Outputs capable of operating standard automotive-style
relays. (Preferably 6)
Compact/Condensed Form-Factor

Finding an Arduino that runs on a 12 V power supply is simple, but finding one that can handle 12 V I/Os has proven tricky.

Using a relay shield for the outputs is straightforward enough, and would be a safe way to step up the output voltage and current (although current is of little concern, given I'm only going to powering the coil in a relay). But what to do about the inputs? I don't want a transistor on each input - that would get quite tedious and large very quickly. Using relays on both sides would work, but most shields are setup to receive coil activation signals from the Arduino and as such also can't handle 12 V inputs, so using a relay shield to step-down from 12 V to 5 V also seems problematic.

Is there an all-in-one I/O solution that can step-down incoming voltages for the board and step-up output voltages on the other side?

What are my best options? I'd prefer not to have to custom-make a shield for such a basic I/O application...

Any and all help is greatly appreciated!


texts:
I connected SIM300cz module's GSM board with Arduino Mega. The GSM board has the pins VCC, GND, RXD, TXD, GND, RI, DTR, STATUS, PWKEY and GND. I connected the GNDs with Arduino's GND, VCC to Arduinos 5V (took power from Arduino), RXD to pin 5, TXD to pin 6 (because of using software serial) and PWKEY to pin 53. My code is as follows:

#include<SoftwareSerial.h>
SoftwareSerial GPRS(5, 6);

int inputPinTempSensor = 0;
float tempCelsius = 0 ;
float thresholdTemp = 45;

void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);  // the Serial port of Arduino baud rate.
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);
  delay(100);
}

void loop() {
  GPRS.print("AT+CREG/r");
  Serial.print(GPRS.read());
  delay(2000);
}

The AT command response should be something like "ok" but it's returning -1 for every loop waiting 2 seconds. Why and what could be the solution?

Edit:

Sorry for the mistakes. I was trying different ways with carriage return and new line characters to make it work. Now the code is:

#include<SoftwareSerial.h>
SoftwareSerial GPRS(5, 6);

void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);  // the Serial port of Arduino baud rate.
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);
  delay(2000);
  GPRS.println("AT+CREG");
}

void loop() {
  while(GPRS.available()){
    Serial.print(GPRS.read());
  }
}

Now it gives no responses at all. Actually after buying the module I was trying with these examples and they were not working either. So, I thought to test if the AT commands were working properly. I could be a problem with my wiring too.


texts:
I have a single function for debugging messages, used through all the project. When KEYDEBUG is defined as 1 or 0, the function is enabled or disabled as required.

#define KEYDEBUG 0

void debugging(int var){
   #if KEYDEBUG
   //Assert
   #endif
}

When checking the compiler, the variable var raises a warning -Wunused-parameter.
How should remove this warning just at this part of the project?
Or which other alternative for using debugging code and removing it from memory for production release?


texts: GSM librarys Software Serial conflicts with I2C pins 2 and 3 for Arduino Micro

texts:
The GSM library apparently uses the Software Serial library to perform the communication. The Arduino Micro specified pins for the serial connection to the GSM is pin 2 and 3 (doc says, but see def of RXPIN below?). I would like to shift this to pin 7 and 8 , with 8 as Rx (has interrupt). However: Changing the definition of TXPIN in GSM3IO.h does not appear to give a working sketch. Also: The pin "number" here, does it refer to PDxx number or other (a bit confused by all the pin names )
.
.

#elif defined(__AVR_ATmega32U4__)
#define __TXPIN__ 7
#define __RXPIN__ 8  /* Previous 3,8,3 ,... but */
#define __RXINT__ 8
#endif


texts: ADC value changing after changing Timer1 value in program

texts:
I'm writing a code where analogRead() reads ADC value from load. After reading ADC value, if it is not in range, I need to manipulate Timer1 value. Which is also getting changed.
But, after changing the Timer value,  if the load value again gets restored, ADC doesn't show the same value again, but shows some other value.

Please refer below code:

#include <TimerOne.h>

int LED = 13;
int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 8;
int OUT4 = 7;
//float A0;
//int OUT5 = 6;
const float refvolt = 5.0;
int volts = 0;
byte tempL_flag = 0;
float samples, loadval, avgacs, acsvaluef =0;
float refval = 2.0;
bool lflag=0;
unsigned long count = 0;

void setup()
{
    pinMode(IN0, INPUT);
    pinMode(IN1, INPUT);
    pinMode(OUT1, OUTPUT);
    pinMode(OUT2, OUTPUT);
    pinMode(OUT3, OUTPUT);
    pinMode(OUT4, OUTPUT);
    pinMode(LED, OUTPUT);
    pinMode(A0, INPUT);
    //digitalWrite(OUT3, LOW);
    Timer1.initialize(370000);
    Serial.begin(9600);
}

word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;
    word avrdata;
    word abcdata;
    byte i;

    for(i=0; i<sample; i++)
    {
        adcdata = 0;
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return(avrdata/sample);
}

void flash_L()
{
    digitalWrite(LED, !digitalRead(LED));
    digitalWrite(OUT4, !digitalRead(OUT4));

    if (digitalRead(OUT4)==1)
    {
        loadval = ADC_READ(10, 10, A5);
        Serial.println(loadval);

        if(loadval < refval)
        {
            Timer1.initialize(185000);
        }
        else
        {
            tempL_flag = 1;
        }
        return;
    }
}

void loop() {

    delay(2000);

    if(digitalRead(IN0)==1)
    {
        Timer1.attachInterrupt(flash_L);
    }
    else if(digitalRead(IN0)==0)
    {
        digitalWrite(LED, LOW);
        digitalWrite(OUT4, LOW);
    }
}


texts: analogWrite causes value from IR receiver to change

texts:
I'm playing around with an IR receiver and an RGB led.

I had it up and running, until I changed around some code. The remote seeming stopped working, but after looking at the values in the Serial Monitor it appeared that the values that were being printed out weren't the same.

After playing around a bit I found that if analogWrite is run on pin 11, the value changes. Why is this so?

Code is as follows:

#include <IRremote.h>

int ir_recv_pin = 2;

IRrecv irrecv(ir_recv_pin);

decode_results results;

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

void loop()
{
    if (irrecv.decode(&results))
    {
        //Serial.println(results.value);
        Serial.println(results.value == CH_MINUS);
        Serial.println(results.value);
        Serial.println(CH_MINUS);

        analogWrite(11, 125);
        irrecv.resume();
    }
}

Output is as such when pressing the button twice in a row (without holding the button down):

1
16753245
16753245
0
3810010651
16753245

Initially the values come out as expected (16753245), but after the analogWrite, the value changes (3810010651).

Looking at the documentation it says that pin 11 runs at 980Hz. Is this why the value changes? If so, why?


texts:
I'm trying to convert a char array to a char. i used this code

char code[4] = {'1','2','3','4'};

char strcode[4];

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

void loop()
{
    memcpy(strcode, code, 4);
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
}

But for some reason when i read my serial monitor i get this:

1234
done

Why are there 2 squares behind it?  Am I doing it wrong?

EDIT: For some reason stackexchange doesn't show the 2 squares but there are 2 squares behind 1234


texts: I want to message and call arduino board. I want some type of automation. But where should I get started I don't know I've tried sim900a module which was disappointing experience for me. Then I found out that this module was designed for asian regions and needed some type of firmware update. I wonder if there are another methods to make calls and send messages to arduino board. Any answers will be appreciated.


texts: My code isn't adjusting the speed of one of the motors and i'm not sure why

texts:
I'm trying to change the speed of motors depending on the amount of light hitting the LDRs. Here i'm trying to make it so that if the LDR has a high value than another, then the motor associated with that LDR slows down so it turns towards the light.

const int motorDirectionA = 9;
const int motorEnableA = 10;
const int motorDirectionB = 5;
const int motorEnableB = 6;

const int leftLDR = A0;
const int rightLDR = A1;

int motorSpeedA = 250;
int motorSpeedB = 250;

void setup()
{
  Serial.begin(9600);
  pinMode(motorDirectionA,OUTPUT);
  pinMode(motorEnableA, OUTPUT);
  pinMode(motorDirectionB,OUTPUT);
  pinMode(motorEnableB, OUTPUT);

  pinMode(leftLDR, INPUT);
  pinMode(rightLDR, INPUT);

}

void loop()
{
  int ldrReadL = analogRead(leftLDR);
  int ldrReadR = analogRead(rightLDR);
  int leftLDRread = ldrReadL;
  int rightLDRread = ldrReadR;

  digitalWrite(motorDirectionA, LOW);
  analogWrite(motorEnableA, motorSpeedA);
  digitalWrite(motorDirectionB, HIGH);
  analogWrite(motorEnableB, motorSpeedB);

  Serial.print("Left LDR reading: ");
  Serial.println(ldrReadL);
  Serial.print("Right LDR reading: ");
  Serial.println(ldrReadR);

  if (leftLDRread > rightLDRread)
  {
    motorSpeedA = 80;
    motorSpeedB = 210;
  }
     else
     {
        motorSpeedA = 210;
        motorSpeedB = 210;
     }

  if (leftLDRread < rightLDRread)
  {
    motorSpeedB = 80;
    motorSpeedA = 210;
  }
      else
     {
       motorSpeedA = 210;
       motorSpeedB = 210;
     }
}

@Maximillian Gerhardt If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.

If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).


texts: How to display variables on 0.96" OLED with u8glib library?

texts:
I have Arduino Uno and 0.96" I2C Oled 4 Pinned display. These are my Arduino codes:

#include "U8glib.h"

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);    // VDD=5V SCL=A5 SDA=A4

int a = 10;

void setup(void) {
}

void loop(void) {

  u8g.setFont(u8g_font_gdr25r);
  u8g.drawStr(8, 30, "E");
  u8g.setFont(u8g_font_gdr25r);
  u8g.drawStr(30, 30,"l");
  delay(2000);

  //  u8g.println(a);  //This code raw is not working
  //  delay(2000);
}

I am trying to indicate integer type variable is called "a" to the OLED screen, but u8glib library hasn't got

  println( (int) a );

function to do this. I only see

  u8g.drawStr();

function that this can't handle integer variables to the display. How can I do that?


texts: Person (phone) detector that trigger an event esp32 cam

texts:
So me and my dad are trying to catch would be thieves and also someone leaving behind alcohol bottles. At his storage business the cameras don't reach to these spots.

Without being too invasive I want to sense bluetooth and/or wifi signals of relatively close phones sort of like a pax counter. This is in lue of using a pir sensor which I have always found finicky and I want to make use of the esp32' cam's wifi/ble chip.

So to start I researched for the past few days or week. I found that most phones don't use ble so maybe that is out. I also found that the esp32 cam is a bit finicky and I'm not sure if it is compatible with other code I have found.

One time I was able to get the light to come on when my phone was near using code I found for the esp32.

Any help or direction would be nice

Edit: I understand this sounds weird but mostly I would just like to get proximity of bluetooth or wifi to trigger an event. The device is powered by battery and I understand not everyone carrys phones.


texts: Two-wire Conductivity Sensor and Arduino Hook-up?

texts:
For the conductivity meter shown in the photo below, it is a non-NPN sensor for measuring conductivity / impedance.

I am trying to figure out the best method for measuring the output of the sensor using an Arduino.

I am told from the supplier that there is no polarity.  I was planning to connect one of the leads through a 10k resistor to an analog input (A0) on my Arduino; and the other lead to 5V?

Without much other information on the sensor, is a 10k resistor a good place to start?


texts: Is Fastled.io library suitable for SMD50500 led strip?

texts:
I was looking for a ready to use library to control my SMD5050 color led strip, and I stumbled across FASTLED.IO library , but after reading trough their website I didn't find anywhere the support for SMD5050 color LED strip. Does anyone knows another "ready to use" animation library? Are FASTLED.IO suitable anyway?
Thanks


texts:
I reinstalled a previously working sketch to my UNO and now the behaviour of the lcd has changed.

Previously this example worked perfectly:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd

  // Print a message to the LCD.
  lcd.backlight();
  lcd.print("Hello, world!");
}

void loop()
{
}

Now it only displays the very first character 'H'

This version does work though:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd

  // Print a message to the LCD.
  lcd.backlight();
  lcd.print("H");
  lcd.print("e");
  lcd.print("l");
  lcd.print("l");
  lcd.print("o");
  lcd.print(" ");
  lcd.print("W");
  lcd.print("o");
  lcd.print("r");
  lcd.print("l");
  lcd.print("d");
}

void loop()
{
}

Can anyone shed me any light what is the reason of this change in behaviour and how to solve it?

Running version 1.8.3 on a W7pro PC


texts: Arduino ,How I can see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0,A1.. pins

texts:
I am working in my project and I want to see the output of my sensors as (0 or 5).
The maximum read was 770 and the minimum read was 0. So, how can I see the  value (0 or 5) on my screen, where I connected my sensors output to analog input A0, A1 pins.
I did the following code, but it didn't work:

void setup(){
Serial.begin(9600);
}
void loop()
{
if (analogRead(0)<385)
      Serial.print("0");
 else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(1)<385)
      Serial.print("0");
   else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(2)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(3)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(4)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(5)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

delay(1500);
}

Note: I have 5 light sensors in my circuit.


texts: Updating Server using ESp8266 with Direction Button Pressed IN

texts:
I've connected a 5-way tactile switch to a ESP8266 module and am using the Arduino IDE to create an automatically updating web server that displays the direction that the button is pressed in when pressed. Currently the webpage displays the first direction that the button was pressed in but does not update the page after I press the button several more times. Below is my code:

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

//ssid and password info, ommitted here for obvious reasons

int upPin = 5;
int leftPin = 4;
int centerPin = 0;
int rightPin = 2;
int downPin = 14;

ESP8266WebServer server ( 80 );

void handleRoot() {
    server.send(200, "text/html", "\
  \
    <meta http-equiv='refresh' content='1'/>\
  \
  \
  \
");   // Send HTTP status 200 (Ok) and send some text to the
browser/client
}

void setup(){
 Serial.begin ( 115200 );
 WiFi.mode ( WIFI_STA );
 WiFi.begin ( ssid, password );

 server.on ( "/", handleRoot );
 server.on ("/", button );
 server.begin();

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

void button(){
  if (digitalRead(rightPin) == LOW)
  {
    server.send(200, "text/html", "
*RIGHT#
");
    delay(10);
  }

  if (digitalRead(leftPin) == LOW)
  {
    server.send(200, "text/html", "
*LEFT#
");
    delay(10);
  }

  if (digitalRead(upPin) == LOW)
  {
    server.send(200, "text/html", "
*UP#
");
    delay(10);
  }

  if (digitalRead(downPin) == LOW)
  {
    server.send(200, "text/html", "
*DOWN#
");
    delay(10);
  }

  if (digitalRead(centerPin) == LOW)
  {
    server.send(200, "text/html", "
*CENTER#
");
    delay(10);
  }

}


texts: How do you write to a specific register using I2C communcation?

texts:
I am trying to write to a charging IC (BQ24193) and I am trying to figure out how to use I2C to write to a specific register so I can set up the charging IC properly. I have watched a few videos on the communication protocol, but I don't understand how to write to a register directly. Your help would be appreciated. Thanks.

Datasheet: http://www.ti.com/lit/ds/symlink/bq24193.pdf


texts: What is the size of the buffer in serial communication with arduino uno?

texts:
as it is in the question, i need to know what is the size of the biggest string that i can send using the serial port to the arduino.
Thank you


texts: loading custom code onto SparkFun Blynk Board

texts:
we're trying to add some code to the SparkFun Blynk Board. We don't want to overwrite the firmware, because that allows it to work with the iphone app, but we need to add our own voids and Blynk. Write commands in order to control this servo RC car via wifi wit the Joystick XY. any ideas?

our code:

#include <Servo.h>
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>
//#define BLYNK_PRINT Serial

char BlynkAuth[] = "6dfb81c116d84003a505056239c23559";
char ssid[] = "Linksys23266";
char pass[] = "roboboyz";

Servo servoR;
Servo servoL;

int pos = 90;

void forward()
{
  servoR.write(110);
  servoL.write(110);
}

void turnRight()
{
  servoR.write(80);
  servoL.write(90);
  delay (2000);
}

void turnLeft()
{
  servoR.write(90);
  servoL.write(80);
  delay(2000);
}

void reverse()
{
  servoR.write(70);
  servoL.write(70);
  delay(2000);
}

void Stop()
{
  servoR.write(94);
  servoL.write(94);
  delay(2000);
}

void setup()
{
  Blynk.begin(BlynkAuth, ssid, pass);  // wifi username and password
  servoR.attach(12);
  servoL.attach(13);
  Serial.begin(9600);
  delay(1000);
}

BLYNK_WRITE(V1)
{
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("; Y = ");
  Serial.println(y);
  if(y>220)
  forward();
  else if(y<35)
  reverse();
  else if(x>220)
  turnRight();
  else if(x<35)
  turnLeft();
  else
  Stop();
}

void loop()
{
  Blynk.run();
}


texts: Arduino Uno programed from a Nvidia Jetson tx2

texts:
I'm trying to program my Arduino Uno with a Jetson tx2 and get the error

avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

The serial port is set to /dev/ttyS0

dmesg when the Arduino is plugged in returns

[78222.855639] usb 1-1: USB disconnect, device number 60
[78224.468387] usb 1-1: new full-speed USB device number 61 using xhci-tegra
[78224.605794] usb 1-1: feature bit otg_vbus_off set
[78224.610575] usb 1-1: New USB device found, idVendor=2341, idProduct=0043
[78224.617365] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[78224.624750] usb 1-1: Manufacturer: Arduino (www.arduino.cc)
[78224.630502] usb 1-1: SerialNumber: 55739323237351306122
[78224.636529] usb 1-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[78224.646057] xhci-tegra 3530000.xhci: tegra_xhci_mbox_work mailbox command 6

lsusb returns

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 054: ID 413c:2107 Dell Computer Corp.
Bus 001 Device 065: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub


texts: Splitting a float into bytes for storage in FRAM (like EEPROM)

texts:
I'm trying to write floats to I2C FRAM (like I2C EEPROM) but without result. I tried with this function but I lose all number after the decimal. Thank's for replying.

This for writing:

float floatNumber = 123.123;
byte floatPt1 = 0;
byte floatPt2 = 0;
byte floatPt3 = 0;
byte floatPt4 = 0;
byte b1 = (floatNumber);
byte b2 = (floatNumber >> 8);
byte b3 = (floatNumber >> 16);
byte b4 = (floatNumber >> 24);

This is for reading:

long floatRicomposto = 0;
floatPt1 = fram.read8(3);
floatPt2 = fram.read8(4);
floatPt3 = fram.read8(5);
floatPt4 = fram.read8(6);
//float RECOMPOSITION
floatRicomposto = (uint32_t) floatPt1 <<  0
  | (uint32_t) floatPt2 <<  8
  | (uint32_t) floatPt3 << 16
  | (uint32_t) floatPt4 << 24;


texts: Arduino Uno + USB Host Shield + Motor Shield

texts: We have an obstacle avoiding robot, and we decided to upgrade it by controlling it with a PS3 controller, so I am asking if above the Arduino UNO we can attach the USB host and above the Host attach the motor shield where the motors are connected to?


texts: Internet connectivity for the Arduino Due using AtmelStudio?

texts: What hardware and software solutions work and what are the tradeoffs for connecting an Arduino Due to the internet?  I gather the ethernet hardware is much cheaper than WiFi hardware (€29 versus €69).  In either case (wired or wireless), what software stacks and drivers work under AtmelStudio?


texts: Arduino gets stuck: battery powered, wireless, dc motor drive

texts:
I have a Arduino Mega 2560 connected to

L293D Motor Driver IC connected to two small size dc motors.
MPU-9150 using i2c
Xbee v1.1 arduino shield by seeed
Li-po battery, 7.4 volts, 2200 mah.

All components are tested separately, they all are working fine, the sensor readings showing data on serial monitor, the l293 drives the motors, xbee sends wireless serial data on pc, and li-po is also working fine.

I have checked the wiring alot of times. It all seems to be correct.

The problem arises when i connect all of them together, since I am using a single power source, I power the l293d with the Li-po and the Arduino also with the Li-po.

When the L293D is powered using Li-po and it starts drawing current from the battery, the serial monitor/arduino gets stuck. It doesnt show sensor readings anymore, while the dc motors start spinning. And they continue to spin, until I break connection with the battery.
Without the l293d powered, the sensor readings are working fine, everything is going normal, as it should, but as soon as the l293d is connected, arduino is stuck..

I have searched alot of forums for this, found some info, perhaps something to do analog and digital ground? mpu-9150 is digital ground. So that is why it stops the arduino mega as the l293d starts drawing current. All hell breaks loose.

Can anybody please help me with this? it is giving me headaches ever since!


texts: expected unqualified-id before '.' token

texts:
//my coding

#include<DHT.h>              // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(14,15,16,17,18,19);
#include<Timer.h>
Timer t;
#include <SoftwareSerial.h>
SoftwareSerial Serial1(2, 3);

#define dht_dpin 12
#define heart 13

DHT dht;

char *api_key="0UXHCZ777V0PAWPW";     // Enter your Write API key from ThingSpeak
static char postUrl[150];
int humi,tem;
void httpGet(String ip, String path, int port=80);

void setup()
{
 lcd.begin(16, 2);
 lcd.clear();
 lcd.print("   Humidity   ");
 lcd.setCursor(0,1);
 lcd.print("  Measurement ");
 delay(2000);
 lcd.clear();
 lcd.print("Circuit Digest ");
 lcd.setCursor(0,1);
 lcd.print("Welcomes You");
 delay(2000);
 Serial1.begin(9600);
 Serial.begin(9600);
 lcd.clear();
 lcd.print("WIFI Connecting");
 lcd.setCursor(0,1);
 lcd.print("Please wait....");
 Serial.println("Connecting Wifi....");
 connect_wifi("AT",1000);
 connect_wifi("AT+CWMODE=1",1000);
 connect_wifi("AT+CWQAP",1000);
 connect_wifi("AT+RST",5000);
 connect_wifi("AT+CWJAP=\"1st floor\",\"muda1884\"",10000);
 Serial.println("Wifi Connected");
 lcd.clear();
 lcd.print("WIFI Connected.");
 pinMode(heart, OUTPUT);
 delay(2000);
 t.oscillate(heart, 1000, LOW);
 t.every(20000, send2server);
}

void loop()
{
***DHT.read11(dht_dpin);     error in this line***
  lcd.setCursor(0,0);
  lcd.print("Humidity");
 **humi=DHT.Humidity;**   error in this line

  lcd.print(humi);   // printing Humidity on LCD
  lcd.print(" %    ");
  lcd.setCursor(0,1);
  lcd.print("Temperature");
**tem=DHT.Temperature;**  error in this line
  lcd.print(tem);   // Printing temperature on LCD
  lcd.write(1);
  lcd.print("C   ");
  delay(1000);
  t.update();
}

void send2server()
{
  char tempStr[8];
  char humidStr[8];
  dtostrf(tem, 5, 3, tempStr);
  dtostrf(humi, 5, 3, humidStr);
  sprintf(postUrl, "update?api_key=%s&field1=%s&field2=%s",api_key,humidStr,tempStr);
  httpGet("api.thingspeak.com", postUrl, 80);
}

//GET https://api.thingspeak.com/update?api_key=0UXHCZ777V0PAWPW&field1=0
void httpGet(String ip, String path, int port)
{
  int resp;
  String atHttpGetCmd = "GET /"+path+" HTTP/1.0\r\n\r\n";
  //AT+CIPSTART="TCP","192.168.20.200",80
  String atTcpPortConnectCmd = "AT+CIPSTART=\"TCP\",\""+ip+"\","+port+"";
  connect_wifi(atTcpPortConnectCmd,1000);
  int len = atHttpGetCmd.length();
  String atSendCmd = "AT+CIPSEND=";
  atSendCmd+=len;
  connect_wifi(atSendCmd,1000);
  connect_wifi(atHttpGetCmd,1000);
}

void connect_wifi(String cmd, int t)
{
  int temp=0,i=0;
  while(1)
  {
    lcd.clear();
    lcd.print(cmd);
    Serial.println(cmd);
    Serial1.println(cmd);
    while(Serial1.available())
    {
      if(Serial1.find("OK"))

      i=8;
    }
    delay(t);
    if(i>5)
    break;
    i++;
  }
  if(i==8)
  {
   Serial.println("OK");
        lcd.setCursor(0,1);
      lcd.print("OK");
  }
  else
  {
   Serial.println("Error");
         lcd.setCursor(0,1);
      lcd.print("Error");
  }
}


texts: Looking for light-weight Arduino OLED library that supports text and bitmaps

texts:
I'm trying to incorporate a screen into my Arduino code which is quite large already. The Adafruit SSD1306 library is overly large and has a lot of unnecessary things in it. I've found the SSD1306Ascii library which is great because it takes up barely any space, but I really would like to be able to display a bitmap logo on the screen. Does anyone know of a library that is light weight but still supports bitmaps?

Thanks.


texts: Digital Potentiometer and Motor Speed Controller

texts:
I'm trying to get a Chinese 20A DC Motor Speed Controller working with a MCP42100 Digital Potentiometer. The analogue potentiometer supplied was 100kOhm. I have programmed my arduino with the following code:

#define DATAOUT     11
#define DATAIN      12       //not used
#define SPICLOCK    13
#define SLAVESELECT 10
#define NOTEON      9
int potValue = 255;
float potInputValue;

void SPIInitialize()
{
  byte clr;
  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK, OUTPUT);
  pinMode(SLAVESELECT, OUTPUT);

  digitalWrite(SLAVESELECT, HIGH); //disable device

  SPCR = (1 << SPE) | (1 << MSTR);
  clr = SPSR;
  clr = SPDR;
  delay(10);
}

char SPITransfer(volatile char data)
{
  SPDR = data;                    // Start the transmission
  while (!(SPSR & (1 << SPIF)))   // Wait the end of the transmission
  {
  };
  return SPDR;                    // return the received byte
}

//--- MCP42100 code

byte SetPot(int address, int value)
{
  // Slave Select set low to allow commands
  digitalWrite(SLAVESELECT, LOW);

  // 2 byte command
  SPITransfer(0x10 + address);   // 0x10 = 'set pot' command
  SPITransfer(value);            // Value to set pot

  // Release chip, signal end transfer
  digitalWrite(SLAVESELECT, HIGH);
}

//--- Application code

void setup()
{
  SPIInitialize();          // Initialize the SPI interface

  Serial.begin(9600);
  delay(25);
  Serial.println("Type a resistance between 0-100 kOhms above.");
}

void loop()
{
  if (Serial.available() > 0) {
    // read the incoming byte:
    potInputValue = Serial.parseInt();
    float potValue = (potInputValue / 100.0) * 255;
    Serial.print("Value: ");
    Serial.print(potValue);
    Serial.print(", Resistance: ");
    Serial.print(potInputValue);
    Serial.println(" kOhms");
    SetPot(1, potValue);
  }

}

Here is a picture of my setup:

Currently at a resistance of 0 kOhms the motor runs at full speed, as it should do and this is how it reacts with the analogue potentiometer. At a resistance of 100 kOhms, the motor (in this case a computer fan) still has enough juice to spin, until I stop it with my finger, but then it doesn't spin without a little push. With the analogue potentiometer, at 100 kOhms the motor received no juice to spin.

Here is a link to the speed controller: http://www.ebay.co.uk/itm/301366805277?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

The speed controller appears to use a 555 timer.

What am I doing wrong with the digital potentiometer to make it so it doesn't behave the same way as the analogue potentiometer?


texts: Advisability of Using Bit Fields in Structs

texts:
I have to track a large amount of data (for an Arduino) in a program while taking care of a fair amount of other business.

I started with a struct like this:

struct MyStruct
{
   // note: these names might as well be foo bar baz
   uint8_t color;
   boolean state;
   uint8_t area;
   uint8_t number;
   uint8_t len;
};

I have an array of 800 of these. At 5 bytes each, that's 4Kb, or half the ram on the Arduino Mega.

I changed to a struct like this:

struct MyStruct
{
   uint8_t color : 3; // max value 7
   // uint8_t state : 1; *** moved, thanks Ignacio ***
   uint8_t area : 5; // m.v. 31
   uint8_t number;
   uint8_t len : 5; // m.v. 31
   uint8_t state : 1; // m.v. 1
};

I understand this reduces the size of each instance to 3 bytes, for a total of 2.4Kb in my array.

I have read that in some implementations / chipsets using bit fields in structs can lead to less efficient execution. Obviously this is a more efficient use of memory, but my question is:

How does the Arduino handle bit fields? Will it be better, worse, or negligibly different in terms or speed when iterating through an array of bit field structs? Is there a good way to test this?


texts: Problem with connecting pins on an Arduino board with an L239D shield

texts:
I have an L239D motor shield just like the Adafruit motor shield. I had a question in my mind. While making a robot, I could not connect my pins from various sensors in Arduino as the motor shield is already fitted on the board. So how can I connect my pins?

PS: I have the same board as shown in the picture


texts: Please explain this OneWire communication with Arduino Uno and DS2502-E48

texts:
The goal is to read the MAC address from a DS2502-E48 chip.

I think I accomplished this goal too with the following code, but I can't get behind at how this works.
I had a similar program with a PIC chip as reference.

I checked several references about OneWire and the DS2502 but not the info I needed to hop to the right memory addresses.
Where'd I normally attain the information so that I know I have to write: cc ,f0 , 0, 10 , read a random byte, and then I'm at the right position for MAC.

#include <OneWire.h>

OneWire ds(2);
void setup()
{
  Serial.begin(9600);

  byte i;
  byte dataLength;
  byte present = 0;
  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
    Serial.print("No more addresses.\n");
    ds.reset_search();
    delay(250);
    return;
  }

  ds.reset();
  ds.select(addr);

  delay(1000);     // maybe 750ms is enough, maybe not

  present = ds.reset();
  if (present != 1 )
  {
    Serial.println("No device present, exiting...");
    return;
  }

    ds.write(0xCC);//SKIP_ROM
    ds.write(0xF0);//READ_MEMORY
    ds.write(0);  // ?
    ds.write(10); // ?
    ds.read();    // ?
    dataLength = ds.read();

    for ( i = 0; i < dataLength; i++) {
    data[i] = ds.read();
    if ( i>3){
      Serial.print(data[i], HEX);
      Serial.print(" ");
    }
  }
}

void loop()
{

}


texts: How do i fix the "A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header"

texts: I have an AI Thinker ESP32-CAM and I've had issues uploading the CameraWebServer sketch, every time I hit upload it says "A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header" and I've tried everything that I can think of, I disconnected and reconnected all the connections on my FTDI board and I've done all sorts of button presses during the connection, I've switched the voltage and I've bought a whole new board and I don't know what the issue is or how to fix it.


texts:
I have a sketch to put to sleep and wake up an Arduino Pro Mini 5V, but the problem is that sometimes when it is moved fast it wakes up itself, thing that I do not want. I have it configure to be waken up in the pin 2 by a rising signal using an interruption:

#define wakePin 2        // pin used for waking up

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, RISING );
}

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, RISING); // 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
    digitalWrite(BLEDPIN, HIGH); //set blue led high
    digitalWrite(RLEDPIN, HIGH); //set red led high

  times = millis();

  if((times-times_f)>=12000)
  {
    times_f=times;
    Serial.println(times-times_f);
    digitalWrite(GLEDPIN, LOW); //Reset the LED's
    digitalWrite(BLEDPIN, LOW);
    digitalWrite(RLEDPIN, LOW);
    sleepNow();
  }
}

I think the problem is that it has a bit of rising signal while moving, so a solution could be to have a threshold in the reception of the signal, can it be done?


texts: Which board to use for wireless communication of small packages?

texts:
I was hoping to get your advice on what Arduino boards to look at for a project I'm working on. The project involves two separate boxes in different rooms of my apartment (~ 5-10 feet away from each other) and needs to allow wireless communication of very small amounts of information (think like 5 bytes). However, this transfer needs to be very rapid (within 200 milliseconds).

While I have worked a good bit with the Arduino Uno, I haven't worked with boards with Wifi capabilities.

The boards I know of are: Esp32, Esp8266, Arduino MKR 1010, Arduino Mega RobotDyn.

What would be the best board for a project like this / are there other boards that are well-suited for a project like this?

Thanks!


texts:
I am currently working on a project which uses PIR motion sensor and 5V relay.
Since you might be familiar that both the motion sensor and the relay requires a 5V connection.

My problem is, I don't want messy connections (parallel and series) and want to use any other pin for power and ground.

Also, can you suggest which resistor I might require for the motion sensor and relay?

Thanks for any help.