http.POST is not sending data to local web page I am using a nodeMCU to send data to my local web page developed using Spring boot but when I run the code I don't get an error the esp8266 connects to WiFi but I don't get anything on my spring boot app or any responses.
Here is the rest controller used from spring boot

@RestController
@RequestMapping("/getallcadres")
public class cadreController {
    @Autowired
    cadreRepository cadre;

@PostMapping("/getnbpassage")
    public String getnbrpassage(@RequestBody String nb){
        System.out.println("nombre de passage = "+nb);
        return "received";

    }
}

and the Arduino code

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(9600);//Serial connection
  WiFi.disconnect();
  WiFi.begin("Iphone de elaa", "27343550");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }
  Serial.println("Wifi is connected");
  Serial.println(WiFi.localIP());

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
 Serial.println("here we start");
   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://localhost:8080/getallcadres/getnbpassage");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("5");   //Send the request
   String payload = http.getString();//Get the response payload

   Serial.println("return code"+httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(30000);  //Send a request every 30 seconds

}

I am using Arduino IDE 1.6.5 here is what I get

Your URL has localhost as the host name. That cannot work. localhost means “self”, the computer initiating the request. In this case it would mean the ESP8266, if it even understood it. You need to use the name or the IP address of the computer running your spring boot app, not localhost.


Connect RGB LED board to Arduino? I'm trying to repurpose an RGB LED (pictured) and use an Arduino board I've just gotten to reprogram the lights. I'm very new to electronics engineering and I don't really know how to get started. How would I connect it to the Arduino? What kind of wire(s) would be best for soldering this to as well as connecting to the Arduino? Can this be programmed like any other LED?
Images:
https://i.stack.imgur.com/u14Bd.jpg
https://i.stack.imgur.com/2inQB.jpg

Connect each of the 3 "L" wires to 3 separate digital IO pins of an arduino e.g. D8, D9, D10 via a resistor say 470 ohms but the value is not too critical. Connect VDD to the arduino +5v.
Use the arduino IDE write a sketch that configures pins 8 9 and 10 as outputs and then see what happens when you send these pins HIGH or LOW. Theres lots more you can do. Good luck.


How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE? I'm debugging a couple of RS232-to-TTL converter boards that I'm trying to use to program my Arduinos and one thing I would like to try would be to reduce the upload serial speed from 115200 to 19200.

How do I do that?

I imagine that there's a setting that can be easily changed on the Arduino IDE preferences. But where is it? But then the bootloader speed would have to match that? How do I change the serial upload speed on optiboot, too?

On Arduino IDE side, the upload speed is coded in hardware/arduino/boards.txt

uno.upload.speed=115200
...

for every kind of board; you cannot change it directly from the IDE (that would be too dangerous as that value must match the expected speed for the actual bootloader of every board).

Now as per the optiboot loader side, the upload speed is defined in BAUD_RATE macro, in optiboot.c:

/* set the UART baud rate defaults */
#ifndef BAUD_RATE
#if F_CPU >= 8000000L
#define BAUD_RATE   115200L // Highest rate Avrdude win32 will support
#elsif F_CPU >= 1000000L
#define BAUD_RATE   9600L   // 19200 also supported, but with significant error
#elsif F_CPU >= 128000L
#define BAUD_RATE   4800L   // Good for 128kHz internal RC
#else
#define BAUD_RATE 1200L     // Good even at 32768Hz
#endif
#endif

So I guess you can:

#define BAUD_RATE 19200 before that block of code
recompile the optiboot loader
upload your own new bootloader version
update uno.upload.speed accordingly in boards.txt
check it on the usual blink sketch and cross your fingers :-)

Please note that this kind of task is not for beginners, you need to know what you're doing.
Also note that I disclaim any responsibility if you get unable to upload programs to your Arduino afterwards!


Power issues with RFDuino I am new to hardware, I have always used plug and play shields to accomplish simple projects. A while back I purchased RGB LED Shutter Shades from Macetech. I got the hacker version thinking I would add a RFDuino and use that to power the glasses and receive commands from my iPhone. I found out that the glasses needed 5v and the RFDuino could only do 3V. So i used a Sainsmart Nano v3 to control the LED's and I added a RFDunio to receive commands from my iPhone, the RFDuino is powered by the Nano.

The issue I am having is that when Im using an external battery pack, the kind you use to charge your phone, I'm guessing the power is not consistent enough and the RFDuino drops its connection to my phone. When I run the glasses using my computers USB port I do not have that problem.

My question: Is there something I can add to my circuit to make this inconsistency with my power stop happening?

I am the designer of the RGB Shades and co-own macetech LLC. The RFDuino specifications claim only 18mA on transmit and receive, so there should not be a current draw issue from that module.

Known power issues with the RGB Shades include high current draw on startup. They can pulse about 1.3 amps (the blue flash) before your software sets them to a more reasonable level. Most USB power packs made today can handle 1.0 amps, some can supply more, but it's still common to find packs limited to 500mA...that would be one thing to check.

Since you are using your own code, please also note that our default code on the controller-included RGB Shades sets the maximum brightness to about one-quarter the actual maximum brightness of the LEDs. This is done to conserve power as well as reduce brightness to non-blinding levels. If your code is attempting to operate at normal brightness, please be aware the RGB Shades could draw up to 4 amps.

The best way to detect the problem would be to get a multimeter and compare the supply voltage when connected to your computer and when connected to the USB power pack.


AT command not send but blue LED stays on I am new to working with Arduino Uno and ESP8266.

Firstly I connected an ESP8266 to an Arduino Uno like so:

TX to TX,
RX to RX,
GND to GND,
VCC to 3.3V,
CH_PD to 3.3V and
adding RESET to GND on the Arduino Uno.

After completing the wire connection, I opened the Arduino IDE serial monitor, where it always shows symbols and text and I set baud rate 115200 and adjusted both NL and CR.

After all of that, when I send an AT command, then no response is shown.

TX is an output. RX is an input.

By connecting TX to TX and RX to RX you have connected an output to an output, and an input to an input.

You need to connect the TXs to the other RXs.

Also: see (NEWBIE) Sending AT Command from Arduino UNO to ESP8266 doesn't work


How to split 12V power suply to arduino and led matrix panel I'm trying to build my Arduino project with Arduino mega and led matrix panel. I'm wondering what power supply should I buy, my first thought was to power the matrix panel from a 5v Arduino pin, but I read here that it's not really a good idea. So now I'm wondering if I can buy a 12V power supply and somehow split it to 6V and 6V (or something like it). To connect one end to Arduino and the other to the matrix panel. If it's possible, how do I do that? Thanks for any help!

No,you cannot split the voltage and expect the devices (Arduino and LED strip) to work correctly together (would lead to different ground levels beside other problems). For getting a different voltage you would need a voltage regulator. A switching "buck" regulator is the better choice here than a linear regulator (lile the one on the Arduino), since it is way more efficient (To get from 12V to 5V a linear voltage regulator would burn up the excessive 7V as heat).
But since both Arduino and LED strip use 5V, why not just buying a 5V power supply, which can provide enough current. Then you can connect it to the Arduino and the LED strip in parallel. No need for voltage regulation in that case.


Why does Arduino round off some integers but not others when my desktop PC does not do this? I am writing (in C) some low level digit manipulation routines that convert int to float and vice versa for Arduino. I came across some puzzling behaviour with Arduino rounding some numbers but not others. So I located and extracted the offending code into a simple program which I compiled on desktop Linux PC with GCC and on Arduino - they give different results. Why?
Here are the programs. The goal is to take the float number 1.3140 and the float number 2.3140 and split them into two integers. In the first case I expect '1' and '3140' and in the second case I expect '2' and '3140' (the terminal '0' is important for my application).
The Arduino code:
void setup() {
double dnum,x,y;
uint16_t intpart,fracpart;

Serial.begin(9600);

dnum = 1.3140;

 x=modf(dnum,&y);
 intpart = (uint16_t)y;
 fracpart = (uint16_t)(10000.0*x);

Serial.println(dnum,4);
Serial.println(intpart);
Serial.println(fracpart);

}

and the output I get is:
1.3140
1
3140

Fantastic! Success. But hold on. If I change the hard-coded number to dnum = 2.3140 I get this:
2.3140
2
3139

What? Why did it round the second part down? Am I doing something fundamentally wrong? So I wrote a little C program for my PC (compiled with gcc). Here is the code:
#include<stdint.h>
#include<stdio.h>
#include<math.h>

int main (int argc, char *argv[])
{
 double dnum,x,y;
 uint16_t intpart,fracpart;

 dnum = 2.3140;

  x=modf(dnum,&y);
  intpart = (uint16_t)y;
  fracpart = (uint16_t)(10000.0*x);

 printf("Int_part = %u\nFrac_Part = %u\n",intpart,fracpart);

 return 0;
}

When run I get this result:
Int_part = 2
Frac_Part = 3140

Now that's what I expect - and to be thorough I also did the above C program with dnum = 1.3140; and I again got the 'correct' expected result:
Int_part = 1
Frac_Part = 3140

So why does the Arduino round the fractional part down when I convert it to an integer sometimes and not others?
I tried this on a genuine Arduino Uno, a clone Arduino uno and a clone Arduino nano and all give the same results. In 'theory' it could be some difference in the compiler tolerance to some coding impropriety I have done (gcc is more tolerant) but can anyone tell me what I did wrong and how to get the Arduino to behave (the way I want it to)? Thanks.

When you cast a floating point number to an integer, it always gets
rounded towards zero. If you want round-to-nearest behavior, you should
use the Arduino round() function.
As to the origin of the discrepancy you see, it comes from two facts:

The numbers you use are not exactly representable as floating point
numbers.
The double on an Arduino Uno is actually equivalent to a float
(32 bits only).

When you write a statement such as dnum = 1.3140;, the compiler stores
in dnum the floating point number that is closest to the decimal
number 1.3140.
Compare:
float32(1.3140) = 1.31400001049041748046875
float64(1.3140) = 1.31400000000000005684341886080801486968994140625
float32(2.3140) = 2.3139998912811279296875
float64(2.3140) = 2.31400000000000005684341886080801486968994140625

Out of these 4 examples, only float32(2.3140) is rounded down.


Assembly on the Arduino: IO registers Question: What registers do I use to access the IO on the Arduino Uno when I am using assembly for programming?

Background:  I was interested in practicing my assembly language skills on the Arduino (I thought it would be easier to turn LEDs on/off than to worry about console IO).  From doing a preliminary search, I have found that the AVR toolchain can be used to program the Arduino.  Yet, I don't quite know how to find the corresponding registers for the IO pins.

The datasheets for the AVR microcontrollers are reasonably good to read. Just Google for the exact controller on your Arduino (eg. ATmege328) and find the "Complete" datasheet on the atmel.com website. Don't download the "Summary", it doesn't include a lot of information. Download the datasheet from atmel.com, that is the only location with the most recent documentation.

There are three registers used in basic IO (check the chapter called "I/O-Ports"):

Where n is a port identifier, a letter ranging from A, B, C, ... depending on the number of IO pins your controller has. Each bit in each register represents a single GPIO pin (yes, you need some basic knowledge on binary to fully understand this).

DDRn, Data Direction Register: This basically configures a pin for either input (0) or output (1).
PORTn, Port n Data Register: When a pin is set as output, the related bit toggles the output pin high (1) or low (0). When configured as input, this enables a weak pull up resistor on the output pin.
PINn,  Port n Input Register: Use this register to read the current level on a pin that is configured as input.


Relay switching problem with ATmega328P + 10 relays I am trying to switch ON/OFF 10 relays connected to ATmega328P via Bluetooth HC-06 module. The problem I am facing is that when I try to Switch ON more than 3-4 relays, some of the previously ON relays switch OFF and the ATmega328 restarts.

I am using a 12V 2A power supply.

I have set up my circuit as shown below

My code

int r1 = 4, r2 = 5, r3 = 6, r4 = 7, r5 = 8, r6 = 9, r7 = 10, r8 = 11, r9 = 12, r10 = 13;
char state;
String msg;
int r = 0;

void setup()
{

    pinMode(r1, OUTPUT);
    pinMode(r2, OUTPUT);
    pinMode(r3, OUTPUT);
    pinMode(r4, OUTPUT);
    pinMode(r5, OUTPUT);

    pinMode(r6, OUTPUT);
    pinMode(r7, OUTPUT);
    pinMode(r8, OUTPUT);
    pinMode(r9, OUTPUT);
    pinMode(r10, OUTPUT);

    Serial.begin(9600);
}

void loop()
{

    while (Serial.available())
    {
      state = Serial.read();

      if (state == '\n')
        break;

      msg += state;

    }

    if (msg.length() > 0)
    {
      /*Serial.print("Data: ");
      Serial.println(msg);*/

      if (msg == "on1")
      {
          digitalWrite(r1, HIGH);
          Serial.print("O1");
      }
      else if (msg == "on2")
      {
          digitalWrite(r2, HIGH);
          Serial.print("O2");
      }
      else if (msg == "on3")
      {
          digitalWrite(r3, HIGH);
          Serial.print("O3");
      }
      else if (msg == "on4")
      {
          digitalWrite(r4, HIGH);
          Serial.print("O4");
      }
      else if (msg == "on5")
      {
          digitalWrite(r5, HIGH);
          Serial.print("O5");
      }
      else if (msg == "on6")
      {
          digitalWrite(r6, HIGH);
          Serial.print("O6");
      }
      else if (msg == "on7")
      {
          digitalWrite(r7, HIGH);
          Serial.print("O7");
      }
      else if (msg == "on8")
      {
          digitalWrite(r8, HIGH);
          Serial.print("O8");
      }
      else if (msg == "on9")
      {
          digitalWrite(r9, HIGH);
          Serial.print("O9");
      }
      else if (msg == "on10")
      {
          digitalWrite(r10, HIGH);
          Serial.print("O10");
      }

      //off---------------------------------------------------------

      else if (msg == "off1")
      {
          digitalWrite(r1, LOW);
          Serial.print("F1");
      }
      else if (msg == "off2")
      {
          digitalWrite(r2, LOW);
          Serial.print("F2");
      }
      else if (msg == "off3")
      {
          digitalWrite(r3, LOW);
          Serial.print("F3");
      }
      else if (msg == "off4")
      {
          digitalWrite(r4, LOW);
          Serial.print("F4");
      }
      else if (msg == "off")
      {
          digitalWrite(r5, LOW);
          Serial.print("F5");
      }
      else if (msg == "off6")
      {
          digitalWrite(r6, LOW);
          Serial.print("F6");
      }
      else if (msg == "off7")
      {
          digitalWrite(r7, LOW);
          Serial.print("F7");
      }
      else if (msg == "off8")
      {
          digitalWrite(r8, LOW);
          Serial.print("F8");
      }
      else if (msg == "off9")
      {
          digitalWrite(r9, LOW);
          Serial.print("F9");
      }
      else if (msg == "off10")
      {
          digitalWrite(r10, LOW);
          Serial.print("F10");
      }
      else if (msg == "offall")
      {
          digitalWrite(r1, LOW);
          digitalWrite(r2, LOW);
          digitalWrite(r3, LOW);
          digitalWrite(r4, LOW);
          digitalWrite(r5, LOW);
          digitalWrite(r6, LOW);
          digitalWrite(r7, LOW);
          digitalWrite(r8, LOW);
          digitalWrite(r9, LOW);
          digitalWrite(r10, LOW);
      }

    }

    msg = "";

    delay(1000);
}

I can see lot of problems.

No decoupling capacitors on ATMega.
Capacitors on both sides voltage regulators are usualy essential for regulator stability.
Big voltage drop on regulator - if it's overheating, thermal shutdown might happen. For example 7V drop @ 350mA (about four relays) results into 2.45 Watts turned into heat.
Bare HC06 doesn't like 5 Volts on its 3.3V logic level input
Xtal oscilator usualy requies two capacitors (22pF) for better stability.


How to see log from Arduino IDE? Where can I see outputs from such instruction in an ino file ?

Serial.println("my message");

The Serial.print statements show up on whatever terminal program is opened and connected. Their can be only one open at a time, but it could the Arduino IDE built in monitor (ctl-shft-m) or an external terminal program, eg putty, or some other program you wrote that opened the com/serial port the Arduino is on.

Remember though - only 1 can be open at a time. If you use an external program you MUST close the com port before attempting to download a new version of your sketch.  If you use the built in monitor/terminal it will automatically do this for you.


Ethernet Shield on Arduino Mini I would like to connect my custom-made Arduino with an Ethernet shield but I'm not so sure I can.
The problem
My board is using the design from the Arduino Mini which lacks the ATmega16U2 which does the USB-to-serial conversion and adds the ICSP pins. I think you get the point... I have only the ATmega328P on the board. Nothing else.
Is it even possible to work my way around it without adding the ATmega16U2? I can't find the chip anywhere on Ebay.

You can just connect the pins used on the shield the the corresponding pins on your custom board. Check the Schematic to see what pins are used for what (and which can be left unconnected)

The only thing you need to lookout for is, that the ethernets shield seems to require 3.3v (the shield has it's own 3.3v regulator, so you only need to connect 5v)

That 16u2 doesn't do anything but usb-to-serial. It's not needed for the ethernet shield.

The ISP header is just 5v, GND, and the 3 SPI pins and reset. But those SPI pins are also broken out to the pins 11, 12 and 13.


Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega? I have an Arduino Mega clone and I haven't used it for a while. I remember it not working so when I plugged it in and tried uploading the code to it and sure enough it didn't work. So I plugged in an Uno and it worked. The Mega is a 2560 Atmel. Here's my code:

#define distanceForward A0
#define distanceLeft A1
#define distanceRight A2
#define distanceRightAngle A3
#define distanceLeftAngle A4
#define distanceBack A5
int talk = 2;

void setup() {
  Serial.begin(9600);
  pinMode(talk, OUTPUT);
  pinMode(distanceForward, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Front Facing
  pinMode(distanceLeftAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left Angle
  pinMode(distanceRightAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right Angle
  pinMode(distanceLeft, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left
  pinMode(distanceRight, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right
  pinMode(distanceBack, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, back
}

void hall_roam() {
  Serial.write("forward");
  if (analogRead(distanceLeftAngle) < 30) {
    Serial.write("right");
    if (analogRead(distanceLeftAngle) > 30) {
      Serial.write("forward");
    }
    if (analogRead(distanceRightAngle) < 30) {
      Serial.write("left");
      if (analogRead(distanceRightAngle) < 30) {
        Serial.write("forward");
      }
      if (analogRead(distanceForward) < 60) {
        Serial.write("stop");
        if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
          Serial.write("left");
          if (analogRead(distanceForward) > 60) {
            Serial.write("stop");
          }
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("right");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      } else {
        Serial.write("forward");
      }
    }
  }
}

void roam() {
  Serial.write("forward");
  if (analogRead(distanceForward) < 60) {
    Serial.write("stop");
    Serial.write("left");
    if (analogRead(distanceForward) > 60) {
      Serial.write("stop");
      Serial.write("forward");
    }
  }
}

void talkbb8() {
  pinMode(talk, HIGH);
  pinMode(talk, LOW);
}

void chill() {
  Serial.write("stop");
  talkbb8();
}

void loop() {
  if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
    hall_roam();
  } else if ((analogRead(distanceForward) < 60) && (analogRead(distanceBack) < 60)) {
    Serial.write("left");
    if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
      Serial.write("stop");
      hall_roam();
    }
  } else {
    roam();
  }
}

If there's a bracket out of place or something it's probably nothing. I'm talking about the characters. Is there anything in the characters that would screw up the upload like the three "!!!" problem I heard about or something like that. It's possible that the USB chip in it isn't recognized by my iMac. If so how do I fix that?

The error message basically means that the programmer is unable to contact the boot-loader on the device. The code you're trying to upload has no bearing on the problem.

There could be one of the four possible reason behind it. They are:

Wrong Port Selected:

If TX/RX led is not blinking, then you may have selected wrong port. If one of both of them are blinking then, you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.
Board is not in Bootloader Mode:

The Arduino Mega is not executing the bootloader for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the board (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the bootloader from connecting.
Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.
Arduino Mega 2560 only: ATmega8U/16U software

Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer toreflash the target.
Hardware damage:

There could be hardware damage to the board, AVR(s), or FTDI chip. Time to buy another board.

You can check this answer.


Float magnet switch interrupts atmega328p and RN2483 sends data It was so easy to my mind but it is really not. I have a float switch which goes high when water is floating. So I connect the switch to INT0 pin of MCU. So when water is not floating everything is OK. When the water is floating I send data. I declare the interrupt as follows:

attachInterrupt (digitalPinToInterrupt (switch), float, RISING);

Where float is

void float()
{
detachInterrupt(0);
digitalWrite (LED, HIGH);
txReturn = myRN.txCnf("1");
}

And my main loop is

attachInterrupt (digitalPinToInterrupt (BUTTON), switchPressed, RISING);
digitalWrite (LED, LOW);
LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

I can't understand why my led is not going LOW and why I interrupt is useless after the first successful time. I am aware that I must keep interrupts routines short and by txReturn.txCnf("1"); I don't but I can not understand where my logic is wrong.

float is already defined for floating point number, so you cannot use it for your function that detects when the sensor is floating on water.  Try calling it something else.

Also, instead of detaching and reattaching the interrupt, use a state machine.  When the interrupt is triggered, you will be able to run different code in the main loop.

unsigned int state;
void setup(){
  state=1;
  attachInterrupt(0,changestate,RISING);
}
void loop(){

switch (state) {
case 1: // do something
// add code here
break;

case 2: // do something else
// add code here
break;
}
}

void changestate(){
if(state==1){state=2;} // interrupt changes state
}


Measure cycle count and time of Digital Input I am currently working on a project which is read a digital input signal from a machine. The machine operation is as below:

when the mold close, the machine gives the "HIGH" signal, when mold is open the machine gives "LOW" signal. A cycle is counted as one cycle when from the mold close --> open --> close.

My goal is to count the cycle and cycle time of each cycle. I am struggling when the Input comes from HIGH to LOW. Appreciate your help to give me some guildance on this project.

int MoldInput = 2;
int MoldState = 0;
int lastMoldState = 0;
int CycleTimeCounter = 0;
int CycleCount = 0;
unsigned long CycleTime;
volatile unsigned long TimeTemp1 = 0;
volatile unsigned long TimeTemp2 = 0;
void setup() {
  // put your setup code here, to run once:
  pinMode (MoldInput,INPUT);
  attachInterrupt(0, RealTimeMoldClose, RISING);
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(CycleTime);
}
void RealTimeMoldClose(){
  unsigned long t = millis();
  TimeTemp2 = t;
  CycleTime = TimeTemp2 - TimeTemp1;
  TimeTemp1 = TimeTemp2;
}

You don't need to do anything on HIGH to LOW. For example, if you are counting how often a door opens you don't also need to count how often it closes, because it must close before it re-opens.

I don't see the point of the interrupt since your code is doing nothing else than checking if the interrupt occurred, so it may as well be checking if the input has changed anyway. This code is simpler:

const int MoldInput = 2;

int lastMoldState = 0;
unsigned long startTime = 0;
unsigned long TotalTime = 0;
unsigned long CycleTimeCounter = 0;

void setup() {
  pinMode (MoldInput, INPUT);
  Serial.begin(115200);
}

unsigned long lastReportedCycleCount = 0;

void loop() {
  int MoldState = digitalRead(MoldInput);
  if (MoldState != lastMoldState) {
    if (MoldState == HIGH) {
      CycleTimeCounter++;  // count times it was high
      TotalTime += millis() - startTime;  // add up time interval
      startTime = millis ();
      delay (100);    // debounce
    }  // end of state being HIGH
    lastMoldState = MoldState;
  }   // end of state change

  if (CycleTimeCounter % 10 == 0 && CycleTimeCounter != lastReportedCycleCount)
    {
    Serial.print (F("Average time after "));
    Serial.print (CycleTimeCounter);
    Serial.print (F(" cycles is "));
    Serial.print (TotalTime / CycleTimeCounter);
    Serial.println (F(" milliseconds"));
    lastReportedCycleCount = CycleTimeCounter;
    }
} // end of loop


TCP connection CPU usage, multiple signals? I'm connecting a client (java program) to an arduino (server). What I want to know is, how high the CPU usage is, and what to do if there are no clients that are trying to connect to arduino? Should I make a delay?

My code looks like this:

EthernetClient client = server.available();

if(client){
    Serial.println("Connected");
    server.write("Hello\n");

    //check if client is still connected
    while (client.connected()){
        Serial.println("Still there");
        delay(2000);
       //check if client received any data
       if(client.available()){
           //read message from client
     }
  }
} else {
     Serial.println("Nope");
     server.write("Hello\n");
     ???????????? delay(2000); ??????????????
}

Thank you for your help.

As the Arduino typically has no demand-based clock scaling, or alternate threads of comparable priority you can schedule, there's really little point in using a delay (which is implemented as a busy-wait) rather than a tight loop - really, the primary appropriate reason would be to reduce the frequency of status output.

However, if you want to design a power-efficient system, you could consider sleeping the CPU between checking if there is anything worthwhile to do, or until an interrupt indicates that there is.  This is not something which delay() will take care of for you, so it is a fair amount of extra work and testing to get right, but it can be very worthwhile if running from batteries.

If your application is not particularly intensive you can also configure the clock divider fuse and slow the chip down generally.


Convert a Bitstring into an integer value I have got a String filled up with 0 and 1 and would like to get an Integer out of it:

String bitString = "";
int Number;
int tmp;

bitString = "";
  for (i=1;i<=10;i++)
  {
    tmp= analogRead (A0);
    bitString +=  tmp % 2;
    delay(50);
  }
// now bitString contains for example "10100110"
// Number = bitstring to int <-------------
// In the end I want that the variable Number contains the integer 166

If you only need the string for printing you can store value in an integer and then use the Serial.print(number,BIN) function to format the output as a binary value.  Appending integers to strings is a potentially costly operation both in performance and memory usage.

int Number = 0;
int tmp;

for (int i=9;i>=0;i--) {
  tmp = analogRead (A0);
  Number += (tmp % 2) << i;
  delay(50);
}
Serial.print(Number, BIN);


Connect BotBoarduino with servos and Ultrasonic sensor HC-SR04 I am new to Arduino and I am making a Walking Quadruped using BotBoarduino as microcontroller.
I want to install an Ultrasonic Sensor HC-SR04 so that it will stop when an obstacle is detected.
I have connected the sensor to Arduino UNO. RX-TX of both the boards are cross-connected. Now I have written this code for UNO:

const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;

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

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;
  // Prints the distance on the Serial Monitor
  Serial.println(distance);

  delay(200);
}

And I am doing this on BotBoarduino:

int byteRead;

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

void loop() {
  while (Serial.available())
  {
    byteRead = Serial.read();
  }

  if(byteRead >= 10)
  {
    walk();
  }
  else
  {
    stand();
  }
}

Whenever distance = 10 or above, let it walk. Else stop.

But it's not working. It's not stopping on obstacles. Sensor is doing its work perfectly, but I think Botboarduino is not getting the values.

Any idea guyz?

You have a misconception, how the Serial interface works.

The Serial interface is basically a stream of bytes (and sometimes start/stop and parity bits, which you normally don't care about) without any structure. This has to be implemented by you.

Also you have to understand, that you don't and cannot know, when a specific byte actually is being send. The fact that you typed a complete string into the serial monitor (or send a string via one call for Serial.println()) does NOT mean, that they are transmitted as a complete packet. The bytes of the string are send one after another and there may be a short delay between two arbitrary bytes. So with your reading while() loop, you are reading bytes until there is a delay long enough for the microcontroller to notice or until the message is send complete. You cannot know, which is the case for this very specific transaction. Also it seems odd, that you are only using the last read byte in your code, since the variable byteRead is overwritten on every while() loop cycle.

Then there is the format, in which you can send data through Serial.

Binary data: Since it is a byte stream, you can directly use the binary values of the bytes to reflect the data. This is easy and good for cases, in which only one value of the size of one byte is transfered every time. So there is no need to distinguish between different parts of the message. In this case you have to use Serial.write() on your sending end. This will write binary data. (You will not be able to see the values in your serial monitor, since it is displaying only ASCII-encoded characters).
ASCII-encoded data string: You are using Serial.println(), which sends an ASCII-encoded string representing the data followed by a NEWLINE character ('\n'). In case of the value 10 you are currently sending 3 bytes: '1', '0', '\n'. In this method, you are using a delimiter character (in this case '\n') to mark the end of a message. On the receiving end you have to read all bytes into a buffer, until you are receiving the delimiter character. Then you can process the message as a whole. In your case you would convert the ASCII-encoded string into an integer variable (for example with the function atoi())

To exactly explain, what is happening with your code: As Chad wrote in his comment, you are trying to use the binary value of a byte, that is an ASCII-encoded character. When looking at an ASCII table, you can see, that there is no printable character with a binary value under 10. So, since you send only printable characters with Serial.println(), There will never be a value, that is under 10.

So now you have 2 options:

Send the variable as binary data in one (!!!) byte (since you are not using distances as big as 255cm the value can fit in there; just make sure, that the byte variable does not roll over) and use every read byte on the receiving end for your code.
Send the variable as ASCII-encoded data with Serial.println() and do the correct processing of the resulting message on the receiving end. Refer to the Serial examples in the Arduino IDE for this. You can directly integrate their code into yours.


which is the number of bits in a float variable Since the maximum value of a float variable is 3.4028235E+38, shouldn't it represented with 128 bits instead of 32? (2^128=3.4028235E+38).

No, it is not integer, so you cannot calculate it that way. It have floating point (not in fixed place).

It is stored as

1.significand x 2 ^ exponent.

It takes one bit for sign (+/-), 23 for significand (0 is not stored it is implicit) and 8 more for exponent.

Because of this, you have fixed precision (number of significant digits) for very large numbers and also for numbers which are close to zero.

You have it all explained here:
https://en.wikipedia.org/wiki/Single-precision_floating-point_format


compare two hex files I need to check if the code burned on the some Arduino is the same one as I have.
I know how to get the hex file from the Arduino. My question is what influence the hex code? Board Type? Microprocessor type? avrdude version? anything else?

The lines in a typical hex file include a VLI (variable length indicator). The hex files output from the IDE might have different lengths than those produced by avrdude. As a simple example:

File 1:

03ABC
03DEF

File 2:

06ABCDEF

Those files will compare differently to each other but convey the same information, split differently between lines.

To do a genuine comparison you would need to account for that.

  Board Type?

Different boards, but with the same processor, might have identical files.

  Microprocessor type?

Different processor would almost certainly have different hex files.

  avrdude version?

Probably not, however see my comments above about the VLIs.

  anything else?

As I said, the compiler may generate lines with (say) 16 bytes per line, but avrdude might read back lines with 32 bytes per line. Thus they would look different but convey the same hex codes, once you allow for that.


How do I set up communication between the "Seeeduino Xiao" and the "Adafruit Bluefruit LE UART Friend - Bluetooth Low Energy (BLE)"? I've seen normal Arduino boards connecting to it no problem (Uno, Nano, etc.). I'm trying to connect it to my Seeeduino Xiao. It has UART compatible pins, so I'm fairly certain wiring isn't an issue. I think I'm having a hard time with the coding.

Nevermind, I figured it out. For anyone that has this problem to:
First, use the "blueart_cmdmode" example file. Then, follow these steps:
HOW TO GET THE SEEEDUINO XIAO TO WORK WITH THIS

Make sure the "Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);"
line of text above the "void error" line is UNCOMMENTED. Everything else in that
block is to still be commented.

Define the pins in "BluefruitConfig.h" as such:
#define BLUEFRUIT_SWUART_RXD_PIN       6    // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN       7    // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN         0    // Required for software serial!
#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused

Wire the pins as defined above.

Make sure the Bluefruit is switched to "CMD" mode.


What happens to the Arduino if you don't use a resistor with an LED? Making a blinking light seems to be one of the most common beginner projects with Arduino. A typical approach is to connect an LED + resistor (in series) to an IO pin, and connect the other end to ground. In code, you make the pin an output, and bring it HIGH and LOW repeatedly to flash the LED.

What happens if you leave that resistor out? Obviously you're going to wreck the LED, but will it also damage the Arduino in some way?

From page 411 of the ATmega328P data sheet, we have a graph of the output current vs voltage.

We can see over the the 20mA range of output currents, we drop ~0.5V, giving an approximate internal resistance of 25Ω.

A typical LED has a forward voltage of about 2V. Therefore, we end up in the situation where we will drop 3V over the 25Ω internal resistance of the ATmega328P, giving an output current of 120mA.

I = (5-2)V / 25Ω = 120mA

This is a simplification, but this 120mA is far larger than the recommended maximum current per pin of 40mA of the microcontroller, and far in excess of what a normal LED should take.

That said, most LEDs and the ATmega328P seem to survive this kind of abuse, especially for short periods. In general, if the pin continues to work after this is done, it should be fine.


Build arduino with windows command line Can someone explain, step by step, along with all software I must use for using Windows command prompt to build an Arduino sketch (.ino file )?

I've followed these steps but I can't.

The command line interface of the Arduino IDE is described in this document

https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc

For example, this command will compile and upload the Blink example to my Arduino Leonardo

./arduino --upload --board arduino:avr:leonardo --port /dev/ttyACM0 --verbose examples/01.Basics/Blink/Blink.ino

Foot note: with IDE 1.6.0, there is an experimental version of the IDE for recent MacOSXs. It doesn't yet support the command line. If you need the command line on Mac, use the recommended version. This will be fixed with 1.6.1


How to include a file from another (parent) directory This is my structure
program/
  src/
    Makefile
    main.ino
    test.h
    ...
  lib/
    i2c.h

In main.ino I include test.h and in test.h I'm trying to include i2c.h but it is just not working, I keep getting:
make: *** No rule to make target 'i2c.h', needed by 'build-uno/main.ino.o'.  Stop.

I tried including like this
// test.h
#include "../lib/i2c.h"

I also tried making a symlink to my lib folder in arduino libraries and adding it as a library in Makefile
sudo ln -s /home/pi/program/lib /usr/share/arduino/libraries/GAVR
# Makefile
ARDUINO_DIR = /usr/share/arduino
BOARD_TAG = uno
ARDUINO_PORT = /dev/ttyAMA0
ARDUINO_LIBS = GAVR
include /usr/share/arduino/Arduino.mk

I also tried making a symlink to lib inside the src directory
ln -s /home/pi/program/lib /home/pi/program/src/lib
None of the above had any effect, the error message stays the same.
How can I include a file from another directory in my program?

This is definitely on the hacky side and not a proper solution to the problem, but it works nevertheless so I'm sharing it.
After making a symlink in the /usr/share/arduino/libraries directory you must make sure that there is a header file with the exact name of the directory, apparently that's how arduino is set up to include them.
In my case my symlink was named GAVR, so I had to create a GAVR.h file inside my lib directory, which would then go ahead and include my i2c.h file and possibly any other file that I'd need.
Also in test.h or anywhere I need to use i2c.h I must include <GAVR.h> instead.
Turns out Also 1 is false, you just need to include <GAVR.h> once in the .ino file and its members will be available everywhere, just like any other library.
Also 2, now that ARDUINO_LIBS is not empty in the Makefile you will need to manually declare all libraries that your code is using.


Arduino Yun used as Wi-Fi hotspot I use for a project an Arduino Yun with Node.JS + socket.io to provide interactivity between a smartphone, driving through a webpage different devices.

I would like to enable this service for several smartphones at the same time. However I would like to work in the very same conditions that a (well configured) hotspot does:

I want to ensure that no user can see the other users on the network,
I want to have a limited number of connections on the Yun at the same time,
I want to force the different users when connected to the Wi-Fi to be routed to a captive portal on the first connection.

Does anyone know first if it is possible with an Arduino Yun (maybe some actions must be performed on a NodeJS virtual server as point 2). If yes, do you have a tutorial or any clues (do I have to use LuCi)?

Last question, in the same topic, I would like to use a fast granted access using NFC tag emulation to provide Wi-Fi credentials. Has anyone tried this with Arduino Yun and a shield?

Finally, here is how I did the job. In short, I separated the two topics of getting a trace of any user using socket.io and giving a limitations of the number of users.

First, my Arduino Yun is on a Ethernet network where a router, acting also as the internet gateway, is a dhcp server. My Arduino Yun have a static IP address in the subnet of this router (so it is not a dhclient). This can be set either by modifying the file /etc/init.d/network.

Including the lines:

config 'interface' 'wan'
        option 'proto' 'static'
        option 'ifname' 'your_interface_name'
        ipaddr xxx.xxx.xxx.xxx

or by using the LuCi interface.

For more information about the way to properly configure the network in OpenWRT, see Network configuration.

Then the router is set to authorize only few IP addresses.

The last step is to bridge the Wi-Fi and the Ethernet (WAN and LAN) keeping the configuration of the Ethernet interface. This can be done using the LuCi interface. Be careful of what interface configuration you keep. How to setup an OpenWRT router as a Wi-Fi bridge to an Ethernet router gives the way to do this.

Note that this can also be done using the Arduino Yun as a DHCP server if you don't want to be connected on a network.

In the end, any connections on the Arduino Wi-Fi will get its IP address in the authorized range (up to 16 users at the same time in my case) by the router/DHCP server through the bridge.

In socket.io, I took the id that is given to any connected client and the IP address to ensure that I have a same user.

About the NFC dynamic tag, I developed a NFC specific board with a dynamic tag in the Arduino Yun/Uno format and its library to push through the bridge between ATmega and Atheros any new Wi-Fi code or any webpage. I think it is outside of this scope so if you need anything about this I can give you in PM.

I finally get at the end a device:

Connected to an existing network and accessing the internet,
Serving the webpages I want using my node serve,
Able to push any information on any other devices on the network through my nodeJS server,
Enabling access to people to local or network content,
Serving some specific local information through the NFC shield.


Does bool return an int? I know that for the Arduino (and C in general) that for comparison sake, "false" is 0, while any non-zero integer is "true". The question that I have is does the bool data type "return" a concrete integer for "true" or "false"?

When I tried Serial.print(true == 1), it printed 1 (which I assumed to be "true"), but when I tried Serial.print(true == 2), it printed 0 (which I assumed to be "false"). When I tried Serial.print(false == 1), it printed 0 and Serial.print(false == 0) printed a 1.

I didn't know if "true" always evaluated to 1 and "false" always evaluated to 0, or if this is not supposed to happen.

If you look at Arduino.h, you'll see true, false and bool defined as:

#define true 0x1
#define false 0x0
typedef uint8_t boolean;

Using a simple test sketch, it appears that comparing true or false to anything besides a 1 or 0 does not "work".

void setup(){

  Serial.begin(9600);

  if(false == 0){Serial.println("false=0");}
  if(false == 1){Serial.println("false=1");}
  if(false == 2){Serial.println("false=2");}
  if(false == -1){Serial.println("false=-1");}
  if(true == 0){Serial.println("true=0");}
  if(true == 1){Serial.println("true=1");}
  if(true == 2){Serial.println("true=2");}
  if(true == -1){Serial.println("true=-1");}

}

void loop(){}


How do I fix this error? It says "warning: invalid conversion from 'long int*' to 'long int' [-fpermissive] I am working on an assignment that converts a reading of force into pounds and then finds the maximum and average of all the values received

This is my code:

void setup()
{

 // put your setup code here, to run once:

 Serial.begin(9600);

  // declare the outputs and inputs
  pinMode( 0 , INPUT);

  //figure out what pin the reading is going to be input to

  fsrReading = analogRead( 0 ) ;
  //the # is the same pin used to get input

  //or use analogRead ( # ), it depends if the pin input is on the analog side of the arduino

  // should this be under the while loop or here?

  //list functions here
  long ForceInPounds(long);
  long FindMax(long);
  long FindAvg(long);

  //declaring variables of functions
  FM = FindMax(new long);
  FA = FindAvg(new long);

        Serial.println("The max value is:");
        Serial.println(FM); //calls FindMax function

        Serial.println("The average value is:");
        Serial.println(FA); //calls FindAvg function

  }

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

 int counter1= 0;

  while (counter1< 100)
  //runs test 100 times

  //should I just make this a function? instead of embedding it in the void loop

 {
      Serial.print("Analog reading = ");

      Serial.println(fsrReading);

      //declaring variable of function used in this segment
      FiP = ForceInPounds(new long);

      Serial.print("Force in Newtons:");
      Serial.println(FiP); //calls ForceinPounds function

      counter1 ++;
  }

}

//FUNCTIONS

long ForceInPounds(const long)
// converts recorded voltage to resistance to conductance to force to pounds
{
 fsrReading = fsrVoltage;

 if (fsrVoltage== 0)
 {
   Serial.print("No pressure");
 }
 else
 {
   fsrResistance = 5000.0 - fsrVoltage;
   //convert voltage to resistance
   fsrResistance *= 10000.0;
   fsrResistance /= fsrVoltage;
   fsrConductance = 1000000.0 ;

   //convert resistance to conductance
   fsrConductance /= fsrResistance;
   if (fsrConductance <=1000.0)
   //convert resistance to conductance
   {
     fsrForce = fsrConductance/80.0;
   }
   else
   {
     fsrForce = fsrConductance - 1000.0;
     fsrForce /= 30.0;
   }
   fsrPounds = fsrForce/4.45;

   //convert force to pounds
 }

 return fsrPounds;
}

long FindMax(long)
{
  int counter2 = 0;

  while (counter2 < 100);
  {
    if ( fsrPounds > maximum)
    {
          maximum = fsrPounds;
          counter2++;
    }
    else
    {
          maximum = maximum;
          counter2++;
    }

  }
  return maximum;

}

long FindAvg (long)
{
  long start = 0;
  //variable to begin avg function
  long avg;
  int counter3 = 0;

  while (counter3 < 100);
  {
    start = start + fsrPounds ;
    counter3 ++;
  }

  avg = start/100;
  return avg;
}

What am I doing wrong? This is my first time working with Arduino.
Thanks

This is most likely not what you want to be doing

//declaring variables of functions
FM = FindMax(new long);
FA = FindAvg(new long);

And it is entirely incompatible with these definitions

//list functions here
long ForceInPounds(long);
long FindMax(long);
long FindAvg(long);

With the result that you pass a pointer to a long (ie, its address in memory), to a function which is instead expecting the value of a long.

However, it's going to be hard to propose a solution until you edit the body of the functions into your question.

There's probably no reason to use new here at all - let the functions allocate their own temporary variables on the stack, since they seem to return a value rather than a pointer.  Most likely even if this worked, the new long you create would be abandoned - ie, a memory leak.


Is it possible to check for correct architecture on OTA update (ESP32 or ESP8266)? Having a skech running on ESP8266 as well as ESP32 with the ability to update via OTA, uploading the wrong binary (upload to ESP8266 compiled for ESP32, and vice versa) leads to crashing the MCU and not being able to do OTA Updates any more.
The Update is done in the simple usual way: Upload binary file and call the methods from the Update Class (begin(), write(), and end()).
Is there any way to check if the uploaded file matches the architecture of the MCU before starting the update?
Edit:
Both the ESP8266 and the ESP32 Updater class check for an "IMAGE_MAGIC" value in the upload header; but that is defined as "ESP_IMAGE_MAGIC = 0xe9" in both cores. So none of them will refuse to update the wrong one.
Edit 2:
Found a simple workaround that satisfies our needs at the moment: As the arduino IDE saves the binaries with a name like <sketch_name>.<board_name>.bin, we just compare the board name as part of the uploaded filename: if (upload.filename.indexOf(MATCH) > 0) ..., where MATCH is the respective board name. As they are pin compatible, we use "d1_mini.bin" and "d1_mini32.bin".
Edit 3:
When the webserver tries to abort the upload with 403 Forbidden (because of wrong file), the browser continues to send data until the upload is done. After that, it displays the error message. Thus, even when the filename does not match, it is a waste of time and bandwidth. The only possibility to avoid this is to do a server.client().stop(), but then the browser will not display the message sent, just something like "connection broken". This does not confirm with the respective RFCs.
This is not really a final solution, so I'ld appreciate any better idea.
Richard

I assume you are the one creating the OTA update.  If so, then why don't you just include a "signature" in the code that is the architecture, i.e. ESP8266 vs. ESP32 and then check for that in your updater code so that it will not install an update for the wrong CPU.


Odd Serial behavior with Uno I'm not understanding what's going on with my Uno. I have a very simple piece of code. no peripherals are connected. Just a bare genuine uno. I program in VisualMicro for Visual Studio.

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

    char stringy[9] = { 0x7E, 0x00, 0x05, 0x08, 0x01, 0x44, 0x33, 0x04, 0x7B };

    for (int i = 0; i < 9; i++) {

        Serial.print(stringy[i]);
        //delay(300);
    }

    Serial.println("");
    Serial.print("done");
}

void loop()
{
    while (1) {  }
}

Without a delay of around 250msec or greater in the for loop, I don't get all the characters. In fact, without the delay, the code doesn't even finish executing. I only get the first character '~'. It doesn't seem to matter what my baud rate is.

This code runs fine without a delay on my Nano. What could possibly be the issue?

You are printing the unprintable.

Do you think it should print:

~0581,34{

or

0x7E 0x00 0x05 0x08 0x01 0x44 0x33 0x04 0x7B

What you will get is

tilde
null
enquiry
backspace
start of heading
comma
three
end of transmission
open brace

I think you can call

Serial.print(stringy[i], HEX);

To see the number you put in come out.


Arduino UNO stuck in Setup function when interfacing UNO with ESP8266 module Following is my code that i am trying to use it with Arduino Uno with ESP8266 module but my code stucked in setup function why is that.

#include "ESP8266.h"
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12,13);
#define SSID        "abcd"
#define PASSWORD    "87654321"
#define HOST_NAME   "www.baidu.com"
#define HOST_PORT   (80)

ESP8266 wifi(mySerial);

void setup(void)
{
    Serial.begin(9600);
    Serial.print("setup begin\r\n");

    Serial.print("FW Version:");
    Serial.println(wifi.getVersion().c_str());

    if (wifi.setOprToStationSoftAP()) {
        Serial.print("to station + softap ok\r\n");
    } else {
        Serial.print("to station + softap err\r\n");
    }

//    if (wifi.joinAP(SSID, PASSWORD)) {
//        Serial.print("Join AP success\r\n");
//
//        Serial.print("IP:");
//        Serial.println( wifi.getLocalIP().c_str());
//    } else {
//        Serial.print("Join AP failure\r\n");
//    }
    delay(500);
    if (wifi.disableMUX()) {
        Serial.print("single ok\r\n");
    } else {
        Serial.print("single err\r\n");
    }

    Serial.print("setup end\r\n");

}

void loop(void)
{
    uint8_t buffer[1024] = {0};

    if (wifi.createTCP(HOST_NAME, HOST_PORT)) {
        Serial.print("create tcp ok\r\n");
    } else {
        Serial.print("create tcp err\r\n");
    }

    char *hello = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n";
    wifi.send((const uint8_t*)hello, strlen(hello));

    uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
    if (len > 0) {
        Serial.print("Received:[");
        for(uint32_t i = 0; i < len; i++) {
            Serial.print((char)buffer[i]);
        }
        Serial.print("]\r\n");
    }

    if (wifi.releaseTCP()) {
        Serial.print("release tcp ok\r\n");
    } else {
        Serial.print("release tcp err\r\n");
    }

    while(1);

}

On Serial Monitor i get the following continuously

setup begin
FW Version:0018000902
to station + softap ok
singl

setup begin
    FW Version:0018000902
    to station + softap ok
    singl

It's always a good idea to put a serial output in the setup of your code.

It seems that your Arduino resets itself.

But why?

I believe the problem would be with too little power for your ESP8266 and Arduino. When the ESP8266 wants to create a network connection, it takes a little more current, possibly leaving your Arduino without enough current to run on itself.

So your Arduino would shut down since the ESP8266 takes up all the current. Creating some kind of bootloop on your Arduino.

Please tell us how you powered the devices and how you connected them.
You might try using a separate power supply or a big capacitor on the Arduino's 5V+GND.


Should I use an accelerometer or gyroscope in my project? A friend and I are working on a sign language translation glove.

Our glove currently successfully uses 5 flex sensors to determine the bend of each finger and can accurately detect letters in the sign language alphabet.

We are now trying to add the functionality to detect one-handed words. Many of these words involve making a letter, but adding some motion. For example, the colour "blue" involves making a B, then shaking/waving your hand in the B position.

We are wondering which type of sensor would be able to handle this. From our research so far, we assume this will either be an accelerometer or a gyroscope, but are not sure which one would be best in the scope of our project.

Any help would be much appreciated!

An accelerometer is a better choice here. For your application, you aren't worried about initial motion but just acceleration. Plus, an accelerometer is cheaper.


Using 2 piezo buzzers to emit the same tone with phase difference For a physics project, I want to record the effect of 2 speakers emitting 100hz at different phase differences. Trouble is, the Arduino can only send one tone() signal at a time. How do I create a phase difference effect using one Arduino?

Since the frequency is so low, you can generate the signals in software.
That would not be as clean as timer-generated signals, but it will be
much easier. And probably clean enough for the intended purpose.

In order to generate a tone, you have to repeatedly switch the pin
connected to the piezo. This is very similar to blinking an LED, only
somewhat faster. Blinking an LED is the very first thing you learn to do
with an Arduino, but you may notice that blinking two LEDs is a
little bit trickier. The problem – and the solution – is
discussed in the Arduino tutorial Blink Without Delay. Building on
that tutorial, here is an example program that generates two 100 Hz
signals in quadrature:

const uint8_t PIN_A = 8;
const uint8_t PIN_B = 9;
const uint32_t HALF_PERIOD = 5000;  // 5000 us
const float PHASE_SHIFT = 0.25;     // 1/4 period

uint8_t state_A = LOW;
uint8_t state_B = LOW;

uint32_t last_A_toggle = 0;
uint32_t last_B_toggle = - 2 * HALF_PERIOD * PHASE_SHIFT;

void setup() {
    pinMode(PIN_A, OUTPUT);
    pinMode(PIN_B, OUTPUT);
}

void loop() {
    uint32_t now = micros();
    if (now - last_A_toggle >= HALF_PERIOD) {
        last_A_toggle += HALF_PERIOD;
        state_A = !state_A;
        digitalWrite(PIN_A, state_A);
    }
    if (now - last_B_toggle >= HALF_PERIOD) {
        last_B_toggle += HALF_PERIOD;
        state_B = !state_B;
        digitalWrite(PIN_B, state_B);
    }
}

If you compare this with the above mentioned tutorial, there are a
couple of differences worth noticing:

The timings are measured using microseconds rather than milliseconds,
for getting a better accuracy
The variables holding the times of last toggle are updated like
last_A_toggle += HALF_PERIOD rather than last_A_toggle = now (the
equivalent of previousMillis = currentMillis). This is needed to
keep an accurate average frequency. Otherwise the time taken to
execute the code would make the frequency slightly off.

There is a little trickery in the initialization of last_B_toggle,
which is an unsigned number initialized to a negative value. The
initialization is valid and works modulo 232. Using a small
positive value would have the ill effect of now - last_B_toggle
overflowing to a very large positive number on the first run of
loop(), putting last_B_toggle effectively in the distant past.


Arduino Pro Mini and GDEW0154T1 ePaper (e ink) display I just got my Arduino Pro Mini and GDEW0154T1 ePaper display (GDEW0154T1 display) and I'm trying to figure out a way to make them "talk". I started reading documentation and multiple sites but I still have no idea. I bought Breadboard, USB connector for Arduino and cables.

I think I need some port to connect display to Breadboard. Could you tell me where to look for it? What next?

Thank you for any advice!

You need to build a special driver board.  Most of the drive circuitry is on the main chip built into the display, which is convenient, but it requires a number of capacitors (which are too big to fit into the display itself) on the various voltage pins, and a special power control circuit to ensure that the different voltages get enabled at the right time.

The datasheet details the capacitors that need connecting (Figure 7.5(2)), as well as the power control circuit (Figure 7.5(4)).

There is another small circuit snippet there as well (Figure 7.5(3), temperature sensor) but I haven't worked out the relevance of that yet.

Also you will need the right FPC connector, and a surface mount PCB to solder it on to, as well as the ability to solder it (reflow oven), so it's not a trivial task.  You may be able to find the right connector already soldered onto a breakout board if you look around - but make sure it is the right one, since there are many variations - number of pins, pitch of pins, upper or lower connection, etc.


How to make the motor move after a certain period of time? Basically I want my motor to run after let's say 10 seconds passed since the program started up.

The amount of time is determined by user input, and I have already coded for that. The motor is connected to a breadboard and powered by a 9v battery, also connected to the breadboard.

The thing is, the motor runs as soon as I connect it to the breadboard. How can I use the Arduino board to make the motor wait 10 seconds before it moves? I am new to both circuitry and code... Sorry for my cluelessness.

Thanks so much.

You will need to add a logic level mosfet of the appropriate size and specs to control the power to the motor.  You can drive the gate of the mosfet from a pin through a current limiting resistor with a larger bleed resistor.  For a brushed motor you'll need a ceramic RF supressor cap plus flyback diode for back EMF protection:

simulate this circuit – Schematic created using CircuitLab

For greater RF supression (if your motor is pretty beefy) you can use a 0.1uF between each input lead and the motor case.

When you turn the pin on, motor turns on, low turns off.  Using analog and appropriate R values you can control motor speed (setting 0-255):

int motorControl = [your pin];

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

void loop()
{
  delay(10000); // delay 10 seconds plus board boot time
  analogWrite(motorControl, 255); // turn motor on full
}

You can time the delay with a stop watch and adjust to be exactly 10s by dropping the delay() call to compensate for the boot up time of the board.

More about MOSFETS here:

https://electronics.stackexchange.com/questions/81935/mosfet-usage-and-p-vs-n-channel


Access is denied. Error compiling for board Arduino/Genuino Uno Having this  error-
Arduino: 1.8.8 Hourly Build 2018/11/30 12:33 (Windows 10), Board: "Arduino/Genuino Uno"

open sketch\LCD.ino.cpp: Access is denied.
Error compiling for board Arduino/Genuino Uno.

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

High likely one of the intermediate/binary files is in use. For example:

When you have it already opened in a debug session
Having it opened in multiple instances of your IDE
Having it opened in another application
Having closed an application that locked the intermediate/binary file(s).

What you can do:

Close the debug session
Close all applications related to the project
Restart your computer


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

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

here is my code:

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

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

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

    void setup()
    {

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

    }

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

    }

Work through your code. When it gets to the target position, your loop looks like this:

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

}

So you say, move to position 'user', then move to position '-stepper2.currentPosition'. Then as the loop comes around you again say move to position 'user', and so on.

The loop will repeat hundreds if no thousands of times per second, so you are basically telling the stepper motor to change direction thousands of times per second which will be why the motor starts vibrating when it gets to the user position.

If, just for the sake of argument, you were to move the first three lines of code in the loop() function to the setup() function, what behaviour do you think you will observe?


Arduino and big servo My dad told me, if i can mount some servo (to control 4 way ventil of heating) to his arduino-controlled home. But there is a problem... The servo does not have a normal 3 cables but 6 and I have no idea how to control. So i start some research about it and i found web site of manufacturer. There was also a Datasheet, but i dont understand it :D. So here is a link to the Manufacture´s web: http://www.mutmeccanica.com/prodottomutmeccanica.php?p=207
And link to datasheet: http://www.mutmeccanica.com/download_file.php?file=downloads/scheda_V70.pdf

And I have a question: Is any hope to connect this to arduino? Is there some shield for it?

In the Arduino world, a servo motor is a RC servo motor. It runs at 5V or 6V and most of them can rotate 180°.

In an industrial environment or with the central heating in a house, the valves are often 24V AC. The most common voltages are 12V and 24V, and most of them with work with DC as well.
Sometimes the term "servo" is used for them, that is for example for a controller for valves with multiple positions.
To control them with an Arduino, the easiest way is with a number of relais.

Some intelligent valve controllers have an input signal. That is the one that you have.
The link to that datasheet is for a valve controller for 24V or 230V AC mains voltage. It has inputs to control it. Depending on the type, the input signal can be 0...5V, to 10V or to 20mA. Which one do you have ?

When that valve is in a central heating, it is possible to cause damage. First of all the central heating is tuned to the house. The valves work together with the pump, and not every system has a automatic overpressure-loop-valve.


Storing a counter to EEPROM - how to extend the life? I am building a circuit that has a button, which when pressed, should increment a counter. I want to store this counter so that when I power off my circuit, it can be read when I power it back on. However, I am worried about the lifetime of the EEPROM - apparently it is only rated to handle 100k writes.

I am using an Adafruit Trinket Pro. Should I cycle my writes through different addresses so as not to write to a single cell over and over? What other strategies are there? I don't expect to be pressing the button many times in a short period of time - maybe at most one press per minute.

Is there some other external storage option I should look at? I really don't want my little project to die randomly one day because I've exceeded ~100k button presses!

If possible use a combination of wear-leveling like algorithm (as pointed out by Mikael Patel) and an power-down driven interrupt, to save onto EEPROM only when needed. At reset, load the last keypress count into a variable in RAM. Increment that variable in RAM on keypress, and save it to EEPROM only when a power down occurs (i.e. the interrupt is triggered). Optionally, when power down occurs, make sure to save the variable only if the new counter actually differs from the old value (i.e. if there actually were keypresses).

To implement the power-down driven interrupt use the built-in comparator to monitor a Vin (use a resistor divider!) against the internal Vref, and use the analog comparator interrupt to save the value. Remember to put enough capacitance between +5V and gnd, to make sure your arduino has enough time to save the state.

Alternatively, if you can afford errors (which might accumulate over time, and lead to a huge underestimation), save the value to EEPROM only every n keypresses.


ESP8266 disconnects after relay switch the aim of the project I'm working on is to water my bonsai automatically, depending on numerous sensor inputs. So basically I have Arduino Nano with huminity and light sensor, a relay to switch the water pump and ESP8266 wifi module, which I use to check the data from the sensors in the Blynk app on my phone. I use two isolated circuits. The first one is used only by the DC motor (water pump) and is supplied by a 5V 600 mA power source. The second takes care of the rest (arduino, ESP, sensors, relay) while it's supplied by a 5V 1A power source. I'm using this with the ESP8266 board.

Once I run the program, it connects to the Blynk server and I can read data from the sensors on my phone. The problem comes when I want to switch the relay from the Blynk app. Than the ESP8266 disconnects (nearly immediately, or after few seconds). I tried a different DC motor (not a water pump) and it worked fine. I also tried to switch the pump without using EPS8266, that worked as well (so the code should be ok). I think this has something to do with the current draw caused by the water pump, but that makes no sense - I'm using two independent circuits, the pump draws maximally 300 mA from the 600 mA source, while the rest of the electronics draws no more than 200 mA from the 1 A power supply. Neither different power supplies, nor another relay worked.

Here's my code:

#define BLYNK_PRINT Serial
#define BLYNK_DEBUG

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

#include <BH1750.h>
#include <Time.h>
#include <SoftwareSerial.h>

#define PUMP  10
#define SENSOR A0
#define BUTTON 2

char ssid[] = "XXXXX";
char pass[] = "XXXXXXXXXXXXXXXXXX";

SoftwareSerial EspSerial(11, 12);
ESP8266 wifi(&EspSerial);

BlynkTimer timer;
BH1750 lightMeter;
int humidity;
int light;
bool pressed = 0  ;
bool pump=1;
char auth[] = "XXXXXXXXXXXXXXXXXXXXXXXXXX";

void sendData(){
      humidity=analogRead(SENSOR);
      light=lightMeter.readLightLevel();
      Blynk.virtualWrite(V0,humidity);
      Blynk.virtualWrite(V1,light);
//      Serial.print("humidity: ");
//      Serial.println(humidity);
//      Serial.print("light: ");
//      Serial.println(light);
}
void checkConnection(){
  if(!Blynk.connected()){
    digitalWrite(PUMP,1);
    Blynk.begin(auth, wifi, ssid, pass);
  }
 }
void checkButton(){
  if(digitalRead(BUTTON) && pressed){
     Blynk.virtualWrite(V3,digitalRead(BUTTON));
     pump=!pump;
//      Serial.println("pump from button");
     }
  else if(digitalRead(BUTTON) && !pressed){
    pressed=1;
    }
  else{
    pressed=0;
    }
}
BLYNK_WRITE(V2)
{
    Serial.println("switching pump");
    pump=!param.asInt();
    digitalWrite(PUMP,pump);
}
void setup() {
  Serial.begin(9600);
  delay(10);
  EspSerial.begin(9600);
  delay(10);
  lightMeter.begin();
  pinMode(PUMP, OUTPUT);
  pinMode(BUTTON, INPUT);
  digitalWrite(PUMP, pump);
  Blynk.begin(auth, wifi, ssid, pass);
  timer.setInterval(5000L, sendData);
  //timer.setInterval(5L, checkButton);
//  timer.setInterval(2000L, checkConnection);
  }

void loop() {
  if (Blynk.connected()) {
      Blynk.run();
      timer.run();
    }
}

and the Blynk log:

[2631095] <[06|05|14|00|00]
[2631389] >[00|05|14|00|C8]
[2632112] <[14|05|15|00|08]vw[00]0[00]632
[2632280] <[14|05|16|00|07]vw[00]1[00]28
[2637109] <[14|05|17|00|08]vw[00]0[00]630
[2637214] <[14|05|18|00|07]vw[00]1[00]28
[2641393] <[06|05|19|00|00]
[2651445] Cmd error
[2656470] Cmd skipped:20
[2656471] Cmd skipped:20

[EDIT] and the circuit:

The problem was hidden in a wrong relay wiring. Once I'm using only COM and NO PIN as it is showed in this article, not only that the whole system is stable and the ESP8266 is not disconnecting any more, but I can also power the circuit using only one 5V 2A power supply.

Here's my updated schematics


How to use an PCF8574P with the simplest code possible i'm having few PCF8574P which i want to use with my arduino and multiplex them however i have no idea how to use the I2C BUS and the IC in general. There are few libraries but they're fairly complex. Is there any library which makes writing and reading from the PCF8574P easy?

Have you given Rob Tillaart's library from the Arduino Playground a try? The demo sketch might look a bit overwhelming, but at it's simplest, all your sketch should need to have to make a led blink like the standard arduino 'blink' sketch is

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

// adjust addresses if needed
PCF8574 PCF_38(0x38);  // add led to P0 (pin 4) (used as output)

void setup()
{
//your setup code here
}

void loop()
{
    //turn P0 (pin 4) of the I/O expander on and off once a second
    PCF_38.write(0, 1);
    delay(1000);
    PCF_38.write(0, 0);
    delay(1000);
}

I don't have any of these parts handy so I can only give generic advice.


What's wrong? FastLED and WS2812B simulation works, physical build doesn't I'm new to Arduino coding and FastLED. When it comes to coding, I'm a complete novice, however, I've been watching YouTube tutorials to help my knowledge. I have successfully run my code on Wokwi, however, when I upload my code to my Arduino, it uploads without error, yet the WS2812B doesn't run the code correctly and appears to freeze after the first pattern.
The LED strip works just run with my Adafruit code, running a very basic set of patterns I created (different than the below code).
Any help would be greatly appreciated! The code below is what I wrote up in Wokwi and the simulation works flawlessly. The only change when uploading to my Arduino is: NUM_LEDS  135
#include <FastLED.h>
#define NUM_LEDS  16
#define LED_PIN   5
#define BRIGHTNESS  255
#define caseCount 7
CRGB source1[NUM_LEDS];
CRGB source2[NUM_LEDS];
CRGB output[NUM_LEDS];

DEFINE_GRADIENT_PALETTE (christmasBlue_gp) {
  0, 0, 0, 255,
  64, 0, 0, 135,
  127, 255, 255, 255,
  191, 0, 0, 135,
  255, 0, 0, 255
};
CRGBPalette16 bluePal = christmasBlue_gp;

uint8_t blendAmount = 0;
uint8_t patternCounter = 0;
uint8_t source1Pattern = 0;
uint8_t source2Pattern = 1;
bool useSource1 = false;

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(output, NUM_LEDS);
  FastLED.setBrightness(BRIGHTNESS);
}

void loop() {

  EVERY_N_MILLISECONDS(5) {
    blend(source1, source2, output, NUM_LEDS, blendAmount);
    if (useSource1) {
      if (blendAmount < 255) blendAmount++;
      } else {
      if (blendAmount > 0) blendAmount--;
      }
  }

  EVERY_N_SECONDS(5) {
    nextPattern();
  }
  runPattern(source1Pattern, source1);
  runPattern(source2Pattern, source2);
  FastLED.show();
}

void nextPattern() {
  patternCounter = (patternCounter + 1) % caseCount;
  if (useSource1) source1Pattern = patternCounter;
  else source2Pattern = patternCounter;
  useSource1 = !useSource1;
  }

void runPattern(uint8_t pattern, CRGB *LEDArray) {
  switch (pattern) {
    case 0:
      movingDots(LEDArray);
      break;
    case 1:
      whiteFill(LEDArray);
      break;
    case 2:
      greenFill(LEDArray);
      break;
    case 3:
      whiteFill(LEDArray);
      break;
    case 4:
      redFill(LEDArray);
      break;
    case 5:
      greenBlueTwinkle(LEDArray);
      break;
    case 6:
      greenRedSplit(LEDArray);
      break;
  }
}

void movingDots(CRGB *LEDarray) {
  uint16_t posBeat = beatsin16(30, 0, NUM_LEDS -1, 0, 0);
  uint16_t posBeat2 = beatsin16(60, 0, NUM_LEDS -1, 0, 0);
  uint16_t posBeat3 = beatsin16(25, 0, NUM_LEDS -1, 0, 127);
  uint16_t posBeat4 = beatsin16(45, 0, NUM_LEDS -1, 0, 127);
  LEDarray[(posBeat + posBeat2) / 2] = CHSV(0, 255, 255);
  LEDarray[(posBeat3 + posBeat4) / 2] = CHSV(120, 255, 255);
  LEDarray[(posBeat3 + posBeat2) / 2] = CHSV(120, 255, 255);
  LEDarray[(posBeat2 + posBeat4) / 2] = CHSV(0, 255, 255);
  LEDarray[(posBeat2 + posBeat4 + posBeat) / 3] = CHSV(0, 0, 255);
  fadeToBlackBy(LEDarray, NUM_LEDS, 1);
}

void whiteFill(CRGB *LEDarray) {
  fill_solid(LEDarray, NUM_LEDS, CRGB::White);
}

void greenFill(CRGB *LEDarray) {
  fill_solid(LEDarray, NUM_LEDS, CRGB::Green);
}

void redFill(CRGB *LEDarray) {
  fill_solid(LEDarray, NUM_LEDS, CRGB::Red);
}

void greenBlueTwinkle(CRGB *LEDarray) {
  EVERY_N_MILLISECONDS(50){
    LEDarray[random8(0, NUM_LEDS-1)] = ColorFromPalette(bluePal, random8(), 255, LINEARBLEND);
    }
  fadeToBlackBy(LEDarray, NUM_LEDS, 1);
  FastLED.show();
}

void greenRedSplit(CRGB *LEDarray) {
  for(int i = 0; i < NUM_LEDS; i++) {
    LEDarray[i] = CHSV(0, 255, 255);
    LEDarray[(NUM_LEDS-1-i)] = CHSV(120, 255, 255);
    FastLED.show();
    delay(100);
    LEDarray[i] = CHSV(0, 255, 255);
  }

  for(int i = NUM_LEDS - 1; i >= 0; i--) {
    LEDarray[i] = CHSV(120, 255, 255);
    LEDarray[(NUM_LEDS-1-i)] = CHSV(0, 255, 255);
    FastLED.show();
    delay(100);
    LEDarray[i] = CHSV(120, 255, 255);
  }
}

Consider what would happen if your power supply is not powerful enough.  Depending on the number of WS2812B you are lighting at the same time you may be exceeding the current rating of your power source.  Using the following quote from this source:

... consider how much current your LED strip is going to pull. With every
single LED on at full brightness, each breakout board can pull about
60mA (20mA per color channel).

We can calculate for a string of 15 WS2812 set to full brightness it would take 15 x 60mA or almost 1 Amp of power.  People commonly source power supply which can handle twice the expected high current load.  So, in this case you would need a supply which can source at least 2 Amps
Also consider not using the Arduino's linear voltage regulator for large current loads.  Not only does it have current limitations but it is also not as effective as a switching power supply. Instead use a power supply of the correct voltage and capable current rating for large current loads.
Try lighting only 1 LED at a time in the strip and stick to one color at a time.  If this works it is likely your power supply is not capable of supplying the necessary current to operate your project as expected.


Micro servo is not working with Arduino UNO I am new to Arduino and trying to do some basic tasks. I want a micro servo to rotate but it's not working, only slightly virbating when I launch a sketch. Below on the photos is how it is all assembled: I have a jumpwires connected to GND, 5V and #8 ports just as in the tutorial. I use micro servo SG-90 and Funduino UNO. Does anybody have any ideas what might the problem be? Here is also the sketch.

#include <Servo.h>

Servo servo;

void setup() {
  // put your setup code here, to run once:
servo.attach(8);
}

void loop() {
   // put your main code here, to run repeatedly:
servo.write(0);
delay(2000);
servo.write(90);
delay(2000);
}

You should not power a servo from a USB port.

However, your most glaring problem is that you have entirely mis-wired the connections, such that no wire is going to the correct place.

Servo connections are in the order of Ground - Power - Signal, usually with a dark color for ground and a redder one for power.  Connector shells aren't standardized between brands, but within one there may be keying to prevent reverse installation.

It would appear that on your servo, ground is brown, power red, and signal orange.

Pull out all three wires and start over; also you'd do well to use a dark color for the ground, as you appear to have mixed up the power and ground as well as the signal.


What transparent casings are commonly used for smaller devices with a display Not exactly Arduino-specific, but if you want to get a daily usable device (instead of a floating wire connection on your table) you eventually want to put your (Arduino-based) device into a nice casing. What are the different types of cases that people use?

I found soap cases as well as kitchen boxes (used one large cheese box from Mepal Rosti).

So far we have used:

ABS cases (pic camdenboss.com):

Small pelicases (convenient to open, pic pelican-case.com):

3D printed cases with a clear perspex window (pic instructables.com):

I've seen other people use laser cut perspex (pic spikenzielabs.com):


SPI conflict with two shields - IOREF? Update:

I've refactored the code to be very resilient to boards missing or not being able to talk to them. Then I tinkered with a bunch of pins and learned that it all comes down to the IOREF pin being connected to the USB Host shield or not. If it's connected, the USB shield "takes over", allows communication with it, but the CAN shield does not work. If the USB shield IOREF pin is not connected, but the rest of the shield's pins are, CAN works. If I disable the IOREF pin going into the CAN shield (and thus the USB shield also since it's on top), the CAN shield works fine still, but the USB shield does not.

Something happens when the IOREF is powered into the USB board and if it's not powered, you can't talk to it.

Original post:

I have the following setup:

Yourduino RoboRED board
Seeed CAN Bus Shield v1.2 http://wiki.seeed.cc/CAN-BUS_Shield_V1.2/
USB Host Shield https://www.arduino.cc/en/Main/ArduinoUSBHostShield

My issue is that if I connect only the CAN bus shield, I can initialize it without any problem, but when I connect the USB host shield on top of the CAN, the CAN shield becomes unresponsive.

I looked into the wiring and per the specs, the following is how the hardware is set up:

SPI bus runs on ICSP header for both shield, not on D11, D12 & D13. I could switch it for the CAN bus shield if I wanted/needed to, but I don't believe I shoudl be.
The trigger pin for the USB host is D10
The trigger pin for the CAN bus is D9 (since it's v1.2 of the board)
Both boards have power. USB board is on top since it does not have an ICSP male connector on the top side, only female on bottom.

I started to debug the code and traced down to this CAN bus function in mcp_can.cpp, which I've instrumented with debug:

INT8U MCP_CAN::mcp2515_setCANCTRL_Mode(const INT8U newmode)
{
    Serial.print("mcp2515_setCANCTRL_Mode with newmode = ");
    Serial.println(newmode);
    INT8U i;

    mcp2515_modifyRegister(MCP_CANCTRL, MODE_MASK, newmode);

    i = mcp2515_readRegister(MCP_CANCTRL);
    i &= MODE_MASK;
    Serial.println("i & MODE_MASK");
    Serial.println(i);
    Serial.println(MODE_MASK);

    if ( i == newmode )
    {
        return MCP2515_OK;
    }

    return MCP2515_FAIL;
}

The output when it fails is:

USB started ok
past SPI begin
mcp2515_init called
mcp2515_setCANCTRL_Mode with newmode = 128
i & MODE_MASK
0
224
Enter setting mode fall
res = 1

For reference, this is the mcp2515_modifyRegister function:

void MCP_CAN::mcp2515_modifyRegister(const INT8U address, const INT8U mask, const INT8U data)
{
    #ifdef SPI_HAS_TRANSACTION
        SPI_BEGIN();
    #endif
    MCP2515_SELECT();
    spi_readwrite(MCP_BITMOD);
    spi_readwrite(address);
    spi_readwrite(mask);
    spi_readwrite(data);
    MCP2515_UNSELECT();
    #ifdef SPI_HAS_TRANSACTION
        SPI_END();
    #endif
}

The whole file is here: https://github.com/Seeed-Studio/CAN_BUS_Shield/blob/master/mcp_can.cpp. I've tried setting SPI_HAS_TRANSACTION to true with no change in the outcome, though I also don't know exactly what this does.

This is my init:

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

    // init can bus : baudrate = 500k

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

    delay( 200 );

    while (CAN_OK != CAN.begin(CAN_500KBPS)) {
        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(10000);
    }

    Serial.println("CANbus ready");
}

It seems to have something to do with the registers available for write by the CAN bus library whenever the USB board is or isn't present. The write fails when the USB board is there. Any thoughts as to why or other things to try would be greatly appreciated.

There's a hardware conflict between these two boards which seems to not be resolvable. The solution was to buy the Keyes USB shield, make sure only it has access to pins 9 and 10 from the Arduino and then wire pin 7 (or 8) into pin 9 of the CAN shield, while also properly initializing the CAN shield with that new pin.

Lastly, the Keyes USB shield's ICSP header isn't long enough, so you need to cut 2 mm off the male non-ICSP pins in order to seat it properly on the CAN shield.


Arduino Serial Monitor displaying weird characters and changes spelling I am recieving the following in my serial monitor. There is a mix of wierd characters then the spelling changes for words once it gets repeated. I don't know why its doing this. my esp01 chip uses 115200 baud rate and the program is 115200 baud rate as well. What is going on.
#include <SoftwareSerial.h>

#define TIMEOUT 5000 // mS
#define LED 5

SoftwareSerial mySerial(7, 6); // RX, TX

const int button = 11;
int button_state = 0;

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

  Serial.begin(115200);
  mySerial.begin(115200);

  SendCommand("AT+RST", "Ready");

  delay(5000);

  SendCommand("AT+CWMODE=3", "OK");
  SendCommand("AT+CIFSR", "OK");
  SendCommand("AT+CIPMUX=1", "OK");
  SendCommand("AT+CIPSERVER=1,80", "OK");
}

void loop() {
  button_state = digitalRead(button);
  mySerial.println(button_state);

  if (button_state == HIGH) {
    SendCommand("AT+CIPSEND=0,23", "OK");

    delay(250);

    mySerial.println("
Button was pressed!
");

    delay(250);

    SendCommand("AT+CIPCLOSE=0", "OK");
  }

  String IncomingString = "";
  boolean StringReady = false;

  while (mySerial.available()) {
    IncomingString = mySerial.readString();
    StringReady = true;
  }

  if (StringReady) {
    Serial.println("Received String: " + IncomingString);

    if (IncomingString.indexOf("LED=ON") != -1) {
      digitalWrite(LED, HIGH);
    }

    if (IncomingString.indexOf("LED=OFF") != -1) {
      digitalWrite(LED, LOW);
    }
  }
}

boolean SendCommand(String cmd, String ack) {
  mySerial.println(cmd); // Send "AT+" command to module

  if (!echoFind(ack)) // timed out waiting for ack string
    return true; // ack blank or ack found
}

boolean echoFind(String keyword) {
  byte current_char = 0;
  byte keyword_length = keyword.length();
  long deadline = millis() + TIMEOUT;

  while (millis() < deadline) {
    if (mySerial.available()) {
      char ch = mySerial.read();
      Serial.write(ch);

      if (ch == keyword[current_char])
        if (++current_char == keyword_length) {
          Serial.println();
          return true;
        }
    }
  }

  return false; // Timed out
}

Your code for the most part looks ok. Your symptoms indicate a Baud mismatch or the receiver is not getting all of the bits. Try doing without the delay's, even reducing them may help. Note when in a delay the processor is committed and cannot do anything else.  See if that helps. 115000 baud is quit hot for the Arduino and software serial. Maybe you can slow things down a little and see if that helps.


Does a pin (input pin Arduino) still float when connected to GPIO on RPI? I am currently testing my application on an Arduino, and I experience floating pin issues. My program reads the pin status of input pins, which are configured as

pinMode(5, INPUT);
digitalWrite(5, HIGH);

but still they tend to float sometimes.

Will this be solved when I connect the pin directly to a GPIO pin on a RPI? Specifically when the application running on the RPI is not active yet (thus the GPIO pin will not actively high or low yet).

Both the PI and and Arduino will be powered at the same time, but the application on the Arduino will be active much faster than the application on the RPI.

So my concern is that while the RPI is still booting and loading the app, the Arduino might still 'suffer' from floating pins, which gives undesirable output to the things my Arduino controls.

Or, will the fact that the RPI and Arduino both have power, share the same ground, will result in a stable input on the Arduino?

PS: not an expert on electronics, hence the question. I can't test this yet as I don't have all the hardware of this project.

You need to enable the internal pull-up resistors which are designed to prevent undefined input states on unconnected inputs.

Change

pinMode(5, INPUT);

to

pinMode(5, INPUT_PULLUP);

For more information on this see Arduino digital pins.


Burn new bootloader without crystal I am considering purchasing these ATmega328 s from
3 pack ATmega328P.

The company says they come with the Arduino UNO bootloader.
I do NOT have any 16 MHz crystals, and I would like to make the chips run on the 8 MHz internal crystal.

I have an Arduino Duemilanove.

Is it possible to burn the minimal setup bootloader from here onto the bootloaded chips without using a crystal?

I've done just that on a Arduino Pro Mini of mine.

You need to change the fuses to have the chip use the Internal Oscillator, instead of a crystal. After that you just program the 8-MHz version of the bootloader. Like the one used in the Arduino Pro Mini 3.3V.

The only problem is that you need to connect a crystal, to change the fuses to not use the crystal. Though it doesn't need to be 16Mhz. Anything between 1 and 16MHz will do.

But since you need to change both the fuses and the bootloader, there is no advantage to buy chips with the bootloader preinstalled.

I'd just buy some bare chips without the bootloader.

PS $4.66 is on the high side for an ATMega328P-PU.


How to use PWM with DRV8870? I'm using Arduino nano and I'm struggling working with the DRV8870 IC on PWM mode.
When I use analogWrite(_pin, duty_cycle); the motor makes weird noises.
I thought it's because of the PWM frequency so I tried to change it using
TCCR1B = TCCR1B & B11111000 | B00000011; but it didn't work out.
Texas Instruments wrote this in their pdf:
"When using PWM, switching between driving and braking typically works best. For example, to drive a motor forward with 50% of the maximum RPM, IN1 = 1 and IN2 = 0 during the driving period, and IN1 = 1 and IN2 = 1 during the other period."
drv8870_pdf

analogWrite(_pin, duty_cycle) will work properly only on pins that support PWM. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11. The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs. Check the following link to find yours:
https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


Arduino Timer Precision I am using the ATMega32u4 to generate multiple pulses at 2.5 kHz. I am using Timer 3, which is a 16-bit timer and using a prescaler of 1, so I have a 0.0625uS resolution. I want to generate pulses with pretty high accuracy and consistency. I have my previous post here, which gave me accuracy. But when I look at the pulse with my oscilloscope it has some jitter. Youtube Video of Jitter.

My final goal is to create a pulse on multiple different pins in this configuration.

What I am assuming is that the reason there is jitter is that there are other interrupts going on in the background, that could be shifting when the pulse stops and starts by a few microseconds. Looking through the datasheet, I found this, which seems to show interrupt priority.

It seems that my TIMER3 COMPA and COMPB are very low down the list of priorities, is there a way to change this priority list? Or is there something else that is causing the jitter?

I have posted my code below:

#define pin2 12
#define pin3 6
#define pin4 8

#define REFRESH 6400

int PULSEIndex;

class Pulse {
  public:
    int pulseLength;
    void Begin(byte GPIO_PIN) {
      pinMode(GPIO_PIN, OUTPUT);
    }
    void writeMicro(double pulse) {
      pulseLength = (pulse * 16);
    }
};

Pulse PULSE1;
Pulse PULSE2;
Pulse PULSE3;
Pulse PULSE4;

void setup() {
  PULSE1.Begin(pin1);
  PULSE2.Begin(pin2);
  PULSE3.Begin(pin3);
  PULSE4.Begin(pin4);

  // Reset Timer 3 Control Register to 0
  TCCR3A = 0;
  TCCR3B = 0;

  // Set CTC Mode
  TCCR3B &= ~(1 << WGM33); //0
  TCCR3B |= (1 << WGM32);  //1

  // Set prescaler to 1
  TCCR3B &= ~(1 << CS32); //0
  TCCR3B &= ~(1 << CS31); //0
  TCCR3B |= (1 << CS30);  //1

  //Reset Timer 3 and set compare value
  TCNT3 = 0;

  // Enable Timer 3 compare interrupt A and B
  TIMSK3 |= (1 << OCIE3B);
  TIMSK3 |= (1 << OCIE3A);

  //Enable global interrupts
  sei();

  //Set Refresh Rate
  OCR3A = REFRESH;
  OCR3B = 1000;
}

void loop() {
  PULSE1.writeMicro(40);
  PULSE2.writeMicro(40);
  PULSE3.writeMicro(40);
  PULSE4.writeMicro(40);
  delay(2);
}

ISR(TIMER3_COMPA_vect) {
  digitalWrite(pin1, HIGH);
  OCR3B = PULSE1.pulseLength;
}

ISR(TIMER3_COMPB_vect) {

  if (PULSEIndex == 1) {
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, HIGH);
    OCR3B += PULSE2.pulseLength;
  }

  if (PULSEIndex == 2) {
    digitalWrite(pin2, LOW);
    digitalWrite(pin3, HIGH);
    OCR3B += PULSE3.pulseLength;
  }

  if (PULSEIndex == 3) {
    digitalWrite(pin3, LOW);
    digitalWrite(pin4, HIGH);
    OCR3B += PULSE4.pulseLength;
  }

  if (PULSEIndex == 4) {
    digitalWrite(pin4, LOW);
  }

  PULSEIndex++;
  if (PULSEIndex > 4) PULSEIndex = 1;
} ```

What I am assuming is that the reason there is jitter is that
  there are other interrupts going on in the background

This seems like a reasonable assumption. Since you are not doing serial
communication, the Timer 0 interrupt is likely the only one triggering
in the background. You can disable it with:

TIMSK0 = 0;

but then all the Arduino timing functions will stop working. You will
have to #include <util/delay.h> and replace delay() with
_delay_ms(). Note that this avr-libc function only works with
compile-time constant delays. On the other hand, it is cycle-accurate
and accepts floating point delays.

  is there a way to change this priority list?

There is not, and even if this was possible, it would not be that
useful. Interrupts in the Arduino are not interruptible: if a
low-priority interrupt is running when a high-priority one triggers, the
high-priority interrupt has to wait for the currently running one to
terminate. Priorities are only relevant when the processor is about to
serve an interrupt request but has to decide which one, among several
pending requests, it will serve first.

Now, a small remark about this:

void loop() {
  PULSE1.writeMicro(40);
  PULSE2.writeMicro(40);
  PULSE3.writeMicro(40);
  PULSE4.writeMicro(40);
  delay(2);
}

There is no point in rewriting those values over and over again. If you
plan to change the code in order to make those widths non-constant, then
you have to take care to:

make the pulseLength properties (or the whole Pulse objects)
volatile
within writeMicro(), disable interrupts while changing
pulseLength.