text:
Motor shield code
I am working on a project using an Arduino Uno and a motor driver shield to move a car with an IRremote. But the vehicle is only moving forward and backward. I want it to move left and right. Kindly help.
This is the code:
#include <IRremote.h>
#include <AFMotor.h>
AF_DCMotor rightMotor(3); // Right motor connected to port 3
AF_DCMotor leftMotor(4); // Left motor connected to port 4
IRrecv irrecv(11);
decode_results results;
#define Straight 0x1FED827
#define Right 0x1FE708F
#define Left 0x1FE30CF
#define Back 0x1FEF00F
#define brake 0x1FE48B7

void setup(){
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    switch (results.value) {
    case Straight:
      moveForward();
      break;
    case Right:
      turnRight();
      break;
    case Left:
      turnLeft();
      break;
    case Back:
      moveBackward();
      break;
    case brake:
      Stop();
    }
    irrecv.resume();
  }
  delay(100);
}

void moveForward() {
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void turnRight(){
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(FORWARD);
  rightMotor.run(BACKWARD);
  delay(400);
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void turnLeft() {
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(BACKWARD);
  rightMotor.run(FORWARD);
  delay(400);
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void moveBackward() {
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(BACKWARD);
  rightMotor.run(BACKWARD);
}

void Stop(){
  leftMotor.setSpeed(0);
  rightMotor.setSpeed(0);
}

What is the problem? Is it that you don't receive the code, that the car doesn't steer, that the motors stop working, ...? Moreover I'd highly suggest you not to use delays, but.. whatever

You need to check if the Right and Left vars are defined correctly. Use serial monitor to show exaclty the value sent when you try to turn right or left.

the power that the motor sheild is providing to the motor in insufficient and the car is not moving.but it making a noise and the serial monitor is giving the correct hexadecimal numbers.

kindly help !!!!!

@SwathiM Sorry but... If you already discovered that "the power that the motor sheild is providing to the motor in insufficient", why are you asking help about the code? Do you think that changing some variables you will be able to move it? First of all let it move, then try to control it. If with a simple "move forward" sketch it doesn't work it's a setup problem. Check the batteries (empty batteries do not have the power to move the motors), check the motor voltage rating (you can't move a 24V motor with 4 AA batteries = 6V), ...


text:
How do I pull up D1-D6 using 10k ohm resistors?
I'm using push buttons to control CR servos (button1=turn CW; button2=turn CCW). How do I pull up D1-D6 and what does that do exactly? I can't find a tutorial that explains it well enough how to use the resistors.

Why do you need to pull up six inputs if you only have two buttons?

use pinMode(D1, INPUT_PULLUP) and save your resistors for something else.

@MarkSmith I've got multiple servos.

Typical Atmel AVR inputs can “float” when left open, that is, may drift high or low.  The idea of a pullup or pulldown resistor is to give an otherwise-open input a definite value – high if pulled up, low if pulled down.
The values of pullup and pulldown resistor values are a tradeoff:   You can use high values to minimize the current that a sensor device must overcome when it switches values, and to minimize power loss in a battery-powered device.  Or you can use low values to get faster switching when you release the input.
There are built-in pullup resistors on most AVR inputs.  (But A6 and A7 on some models of ATmega328's don't have pullups.)  To use a built-in pullup, initialize the input pin with (for example) pinMode(mypin, INPUT_PULLUP) instead of pinMode(mypin, INPUT).
To sense the state of a simple normally-open switch, you would connect one side of the switch to an input, and the other side to ground.  Initialize the pin to be a pulled-up input: eg, pinMode(mypin, INPUT_PULLUP).  Regard the switch as not-pushed when digitalRead() shows HIGH, and  pushed when it shows LOW.
If you really want to use external pullup resistors, connect the switch as above – one side to ground, one side to a pin – and connect a resistor between +5 V and the pin.  That is, one end of a resistor and one side of a switch will connect to the input pin.  In this case, use either INPUT or INPUT_PULLUP as the pinMode setting; it makes no big difference because the internal pullup resistor has a fairly high value, eg 40 KΩ.

Do you think for this Thing - https://www.thingiverse.com/thing:239105 - I can use internal pull-up resistors? It's telling me to use external, but I don't understand why. Thanks for your help!

I don't know what D2-D6 (which that page refers to as having pull-ups) are used for in that project.  If it's switch or rotary encoder inputs, internal pullups should be fine.   If it's I2C, maybe not.  Anyhow, I didn't find a link to a circuit diagram that might reveal how D2-D6 are used.  Do you have a circuit diagram or a link?

The trouble is that there isn't a circuit diagram. D2-D6 are going to the buttons and joystick on a shield (https://www.sparkfun.com/products/9760). When you press those buttons or move the joystick CRservos will move clockwise or counter-clockwise.

That sparkfun.com/products/9760 page says internal pullups are ok:  “The momentary push buttons are connected to Arduino digital pins 2-6; when pressed they will pull the pin low (utilizing the internal pull-ups of the Arduino)”

That's great! Did not see that. There doesn't seem to be any benefit to using external pullups.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
maintain state of a channel cd74hc4067
I have this code to change channels.
void setMuxChannel(byte channel) {
   digitalWrite(muxS0, bitRead(channel, 0));
   digitalWrite(muxS1, bitRead(channel, 1));
   digitalWrite(muxS2, bitRead(channel, 2));
   digitalWrite(muxS3, bitRead(channel, 3));
}

I have this code to write a value in a channels, but when I change to a new channel, the previous channel returns to LOW.
I want to turn on LEDs using multiplexer, however the LEDs do not stay on since the channel they are connected to does not keep its value.
  setMuxChannel(1);
  digitalWrite (muxSIG,a);
  delay(5);
  setMuxChannel(2);
  digitalWrite (muxSIG,b);
  delay(5);
  setMuxChannel(3);
  digitalWrite (muxSIG,c);
  delay(5);
  setMuxChannel(4);
  digitalWrite (muxSIG,d);

What are the values of the variables a to d? And what LEDs? How have you connected them? Provide a schematic for this

You don't want a mux for this job. A shift register would be better.

You can't do that with a multiplexer, unless you scan across all channels really fast.

The whole point of a multiplexer is to only connect ONE channel at a time to the input. It is designed to send many different signals through one wire by time sharing. Normally data in some form is send, and not the direct control current of a simple load. So you will not be able to drive more than one channel at a given time.
You can cycle very fast through the channels to let it seem, as if the LEDs were on simultaneously, but this will decrease their light intensity.
If you just want to drive some LEDs without using too mich of the IO pins, you should follow Majenkos comment and use a shift register instead. They can drive all outputs at the same time if wanted. Also often they can be daisy-chained to simply controlling multiple shift registers through a single output of the Arduino.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Why is 8x8 matrix pins do not correspond to rows and columns order?
It would be easier to program led matrix if 1-8 pins corresponded to 1-8 rows and 9-16 pins corresponded to 1-8 columns.
Instead there is the following arrangement:

Why is it made like this?

It's probably easier to manufacture, other than that, I don't see why.
If this is a serious issue, you can contact your manufacturer, since he is most likely to know why.
You can:

Work around the issue, by wiring pin 1 to input 9, pin 2 to input 14 etc.
Make a software solution like:
#define ROW1 9
#define ROW2 14
Buy an LED-matrix that has the pins in the correct order (check the datasheet before purchase).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Using MCP23017 to control Servos
Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question
" how can I do this with a MCP23017 ? ".
I have searched the web a fair bit but no luck.
Is there a modified Servo library out there??
It's such an obvious solution i figure it must have been done before.
Any suggestions..Thanks.

Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question " how can I do this with a MCP23017?

The Servo library could be modified to allow toggling of GPIO pins on a MCP23017 but there are some issues with timing.
The library uses Timers and Interrupt Service Routines (ISR) to handle the pulse width. The servo pin is toggled in the ISR.
At 100 KHz (100 Kbps) I2C at least 3 bytes need to be transmitted to the MCP230017 to toggle a pin. That is approx. 300 us and not possible to do from the Servo ISR. Another execution pattern is required.
Cheers!

Thank All for the feedback...modifying a library is not an option at this time...not that good yet...The more research I do the less likely the option seems so I will cheat and purchase a 386 MEGA board...54 I/O's is sufficient for my needs on this project. 13 Servo (seperate power supply) and 28 repeater LED's ....track side LED's will be handled by MCP23017 x 2 in series. I was using the Adafruit 16 servo board but I think I fritz-ed it. Oh well thats life.

how can I do this with a MCP23017 ? ".

you can but it would be fairly expensive in processing power, as you need to keep track of both rising and falling edges of every channel at all times, and send the data to the chip -> may not be doable given i2c's speed limitations.

I have searched the web a fair bit but no luck.

I wrote a variety of approaches / implementations on driving multiple servo channels off of one timer, with or without output compare, here: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/
it will branch out to a few other variants, depending on resources available to you.

Theoretically, yes. It would be pretty interesting to see, but running multiple servos would account for a huge amount of what you can reasonably do with your code and probably be a huge headache.
Perhaps a better solution would be to use a PWM expander like the PCA9685.

For PWM, the MCP23017 would have to be software-driven.
I would suggest one of the PCA9685 boards, which give you hardware PWM (and can also provide digital pins).
These are a bit more expensive, but very easy to use, and are driven by I2C in the same way.

Indeed, the PCA9685 is used to control servos, I also use them to dim lights with an array of mosfet switches !

For example...
unsigned long long servo_timing[2]={0,0};
int A_data=0;
void servo_ini()
{
  Wire.beginTransmission(0x20);
    Wire.write(0x00);      // address bank A
    Wire.write(0x00);
    Wire.endTransmission();
}
void servo_set(unsigned int servo_tim,bool servo_mod){
   if(servo_mod==1){
    servo_tim=map(servo_tim,0,180,200,1900);
   }
   //if(servo_vector<=0)/*lcd_tim=650;*/servo_tim=220;/0
   //if(servo_vector==1)/*lcd_tim=1400;*/servo_tim=1000;/90
   //if(servo_vector>=2)/*lcd_tim=2255;*/servo_tim=1870;/180
   if(micros()-servo_timing[0]>servo_tim)
   {
     A_data&=0b11111110;
     Wire.beginTransmission(0x20);
     Wire.write(0x12);      // address bank A
     Wire.write(A_data);
     Wire.endTransmission();
     if(micros()-servo_timing[1]>(20000-servo_tim))
     {
       A_data|=0b00000001;
       Wire.beginTransmission(0x20);
       Wire.write(0x12);      // address bank A
       Wire.write(A_data);
       Wire.endTransmission();
       servo_timing[0]=micros();
       servo_timing[1]=micros();
     }

  }
}

I succeeded in pwm (servo control) with mcp23017.
Moreover, it is 16ch.
The mcp23017 in the Arduino Library also has a wordwrite write, but the frequency still couldn't catch up.
There is no choice but to create a library by yourself and generate a pulse of 0.5msec .. 2.5msec in 20msec 50Hz to drive the servo motor.
We are currently organizing the library
thank you
https://twitter.com/chrmlinux03/status/1534834169737789441?s=20&t=EqkVXJ2v1H3i_tfZsXfjHQ
https://github.com/chrmlinux/

authors: вячеслав пулатов

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Using ALL the analog pins on Mega for Servo
I wish to use ALL the Analog pins on a Mega2560 R3 to control Servo's, all is well up to and including A9, but from there on nothing. {sound familiar} this is apparently not a new problem. I have tried Servo.h and MegaServo.h but still no luck, does anyone have info on a library that will do this or a method to get around it........all the pins on the end buss are used for other purposes and are not available. I can post the code, but first just asking the general questions. Thanks Doug

OK..Solved...tried a library I had previously discarded for another project but it works with this situation..SoftwareServo ....(had also tried versions of Servo and MegaServo with no luck) I have attached a proven sketch that shows the method using arrays (as i have 16 servos to control) hope this is of use to others.
    /*This sketch will enable you to use ALL of the Analog pins on a Mega2560 to control a Servo
 * it uses the Arrays and the Softwareservo.h as the other Servo libraries do not support
 * Mega Analog above A9
 * this is the only method i have found that works
 * hope this is of use to others.
 */
#include <SoftwareServo.h>

SoftwareServo servos[16];  // create servo object to control a servo

int pos=0;
int servoPins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,A14,A15};                    //servo pin numbers
int servoPosMin[] = {80,80,80,80,80,80,80,80,80,89,80,81,80,70,80,45};                        //servo lower setting to suit individual servo
int servoPosMax[] = {100,100,100,100,100,100,100,100,100,100,100,100,100,110,100,160};        //servo upper setting to suit individual servo
boolean refresh = false;  // toggle refresh on/off
int m = 0;
int p = 0;
void setup()
{
  Serial.begin(115200);
  for (m=0;m < 16;m++) {
      // attaches the servo on pin to the servo object
    servos[m].attach(servoPins[m]);
      // init angle of servo inbetween two limitations
    servos[m].write(((servoPosMax[m]+servoPosMin[m])/2));
    Serial.println(m);
    delay(10);
      SoftwareServo::refresh();
  }
}
void loop()
{
  for (p=0;p < 16;p++) {

    for (pos = servoPosMin[p]; pos <= servoPosMax[p]; pos += 1) { // goes from 0 degrees to 180 degrees
      servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
      delay(15);                                                  // waits 15ms for the servo to reach the position
      Refresh();
  }
    for (pos = servoPosMax[p]; pos >= servoPosMin[p]; pos -= 1) { // goes from 180 degrees to 0 degrees
      servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
      delay(15);                                                  // waits 15ms for the servo to reach the position
      Refresh();
    }
  }
}
void Refresh() {
  refresh = refresh ? false : true;                             // set refresh one time / 2
  if (refresh) SoftwareServo::refresh();
  Serial.print("Servo Number = ");
  Serial.println(p);
  Serial.print("  Angle =  ");
  Serial.println(pos);
}

There seems to be something quirky about this, the line "servos[m].write(((servoPosMax[m]+servoPosMin[m])/2));" in Setup() accepts the value but doesn't execute until it runs the void.loop() at the first servo.write command. How can I preset the servo position in void.setup() with this action the way it is??

There is a relatively easy fix, you need to change one symbol in the library code, in Servo.h:
Change
typedef struct  {
   uint8_t nbr        :6 ;
   uint8_t isActive   :1 ;
 } ServoPin_t   ;

To
typedef struct  {
   uint8_t nbr        :7 ;
   uint8_t isActive   :1 ;
 } ServoPin_t   ;

Pull request here: https://github.com/arduino-libraries/Servo/pull/11


text:
Connecting external mic to the Teensy
I have a Teensy 3.2 and the Teensy audio board.
I was going to connect lavalier microphone to its audio jack but learned that it's only for output.
There are line-in pins though (see "Back Side" scheme). And MIC+GND pins, but these are for, ehm, radio parts microphones, I guess?
Being a complete novice I have no idea how to connect microphone jack (or audio connector) to line-in pins and whether I would need an amplifier between microphone and pins. If so then probably I just can't do it.
I would be grateful for detailed instructions.

It is easier than I thought! I soldered audio jack to MIC+GND, inserted microphone in and it works!
And pretty well :-)
Cheap random lavalier model: Panasonic RP-VC201. I guess any consumer model will do.


text:
Arduino write/handle long programs
I'm writing a "sketch" in the Arduino IDE which has at this very moment 1500 lines and is going to become much longer. I splitted it in several tabs, but that's not very comfortable to use (I need to find the "precompiler" file in a temporary folder in order to have my program in a printable version, in the tabs bar I can't see all tabs, ...).
Are there any better alernatives to the Arduino IDE? Someone suggested me PlatformIO, is that a good IDE? (please note that I have a mac running OS X 10.12.1; I also have a (virtual) Windows 10 machine if absolutly needed, but I'd like to install the IDE on MAC OS X)
What are the best ways to create a long program? In general, for C++, what are the best practices? And is for Arduino the same?

In the arduino IDE you can set the option "use external editor". Then you can use your own favorite editor, like Notepad++ or Sublime Text. You will then only use the Arduino IDE for compiling and uploading.

Instead of keeping all the 1500 lines in a single .ino, why not creating your own library with its .cpp and .h files ? It is quite easy when reading  that "Arduino Libraries - Manual installation".

Give a try to Platformio. It's based on the Atom editor. It's great and multi platform (mac, windoze, linux)
As for splitting your program, it is a good idea but not any ways. Keep concepts in the same file, avoid using globals are just a few hints.

I can't help but recommend UECIDE, but then I wrote it. It's better than the Arduino IDE at working with large projects with multiple files, yet not as complex as things like Atmel Studio.
I would, however, recommend a re-think about how you arrange your project. A single long file (even if made from multiple files joined together) isn't good. Instead you should split your project into a number of modules. Consider writing libraries for some of the functionality of your program.
No one in the real world wants a massive program as one single file. All big projects are made out of multiple files, and those files are all separate units and compiled separately. The fact that the Arduino IDE joins them all together into one gargantufile is IMHO a bad idea. Keep things separate. Keep things modular. Keep things as they are in the real world of development.

Yes, I personally experienced that a single file isn't good at all. What would be a good way to create separate units? Is the creation of libraries the only way to do that?

The creation of libraries is a good way to do it, though editing them can be more difficult than using the IDE. It's easier in UECIDE since you can have libraries embedded within your sketch and edit them in the IDE.  Just making C++ instead of INO files (.cpp instead of .ino) in the normal Arduino IDE keeps things separate too.

@Maximus suggested Atmel Studio. WHile this choice is not bad, the programming language, well at least if you are used to the "Arduino type" C, is different then Arduino. An easy way to get all of the things you are used with Arduino to an other IDE is Visual Micro.
This IDE is deffenetly an upgrade. It has code completition and is just more adapted for programming (thats in my opinion). A good thing that I like about it is that it will still pass by the Arduino IDE's compiler.
BTW, you'll need to have Visual Studio.

authors: Рынок Падает


text:
Using Serial as boolean function argument
The following program compiles in the Arduino IDE.
void doSomething(bool) {}

void setup() {
  doSomething(Serial);
}

void loop() {}

But, as expected, this one doesn't:
class MyClass {};

void doSomething(bool) {}

void setup() {
  MyClass myClass;
  doSomething(myClass);
}

void loop() {}

The compiler returns the error cannot convert 'MyClass' to 'bool' for argument '1' to 'void doSomething(bool)'

Why is it possible to compile the former? Isn't Serial a normal class instance (of HardwareSerial)? Does it makes any sense to interpret Serial as a bool?

You did not look up the documentation, did you? That's why I voted down.

@thebusybee Nevermind the downvote, but I disagree on your reasoning (and the slightly arrogant rethorical question). I think Arduino world (including its stackexchange site) is a great place to learn the basics of coding, and navigating trough the documentation to the solution of a question such as this one is a skill that must be learned, it is not obvious to a beginner

Well, as in any other case including non-programmer software, your first stop is always the provided documentation, and not a random web search engine, StackExchange site, or even ChatGPT. I notice each day that this skill is fading away, though. All the best and good luck!

HardwareSerial defines operator bool(), which allows it to be used in a boolean context.

Classes define whether and how their instances can be converted to bool, and what the resulting bool means.
In the specific case of HardwareSerial, it means the serial port is ready: "This will only return false if querying the Leonardo's USB CDC serial connection before it is ready." See the documentation of if(Serial).

And what is the purpose of the bool() operator?

Classes define whether and how their instances can be converted to bool, and what the resulting bool means. In the specific case of HardwareSerial, it means the serial port is ready: "This will only return false if querying the Leonardo's USB CDC serial connection before it is ready." — https://www.arduino.cc/en/Serial/IfSerial

Adding to the answer, you can make this kind of wizardry happen with your classes/structs like this (well, the answer already gives you the way with a link, but I just felt like adding it here).

Doing a User-defined conversion function (the way Cppreference calls it here)
to define your custom cast, you just do a member like this
operator <desired-type-here> ()

Example: suppose we have a class Integer that we want to use as a bool in an if statement like this one if(x):
class Integer {
public:
    Integer(int x) : val{x} {}

    int val;
};

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

// look here
void loop() {
    Integer x(42);
    if (x) { // This line will obviously error out
        Serial.println("I swear I forgot what 42 referenced, darn it.");
    }
    else {
        Serial.println("0 is a very powerful number");
    }

}

now, let's implement our custom cast in the function like this:
class Integer {
public:
    Integer(int x) : val{x} {}

    // here, wizardry will happen
    // NOTE: The "const" here it's optional. You can write it if you desire to
    // allow it to be used with "const Integer"
    operator bool() const {
        return (val != 0);
    }

    int val;
};

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

// look here
void loop() {
    Integer x(42);
    if (x) { // now this works and will print the true statement.
        Serial.println("I swear I forgot what 42 referenced, darn it.");
    }
    else {
        Serial.println("0 is a very powerful number");
    }

    bool yes = x; // this statement is also valid now since "x" gets casted to bool and the result gets assigned to "yes"
}

Extra: You can also make it so an explicit cast is necessary to use the conversion function by adding explicit to the function declaration like this:
explicit operator <desired-type>()

Let's say you want your Integer class to be casted to a float, but you want to state when the cast happens explicitly. So, we would modify our class like this:
class Integer {
public:
    Integer(int x) : val{x} {}

    // We.. will comment this here because the compiler will try to cast
    // Integer to float by first casting it to a bool and then cast that bool
    // to a float. You can also make it explicit so it doesn't happen (but
    // remember that you will need to cast explicitly)
    /*operator bool() const {
        return (val != 0);
    }*/

    // Let's do more magic here
    explicit operator float() const {
        return static_cast<float>(val); // "(float)val" also works, but the uglier the cast syntax is, the easier it is to find it in the code which seems to be considered better.
    }

    int val;
};

and now we can do this in our code:
void loop() {
    Integer x(42);

    float y = x; // The compiler will judge your past actions for this.
    float z = static_cast<float>(x); // The compiler will happily accept this.

}


text:
Low memory error using SD card
I called HTTP web service on Arduino Uno, now i am trying to store the data in SD card. But as soon as i compile the program, it shows LOW MEMORY error and no data stored in SD card.
Any one can help?

Use a board with more memory. Both those operations use a lot of RAM for buffers.

Please suggest the board.

How do you copy the data? It's very unlikely that your UNO can copy all the data at once.

Try Arduino mega. It has more memory 8 KB RAM, 256 KB flash memory.

Try to use properly  kind of variables for example if u r using Int in a value can would  use byte of try to put some serial.println(F("wherever  you can print "))  for running  on sram instead of  stack memory.

Tried to put serial.println(F(" ")) but still same problem.

If it still gives the same problem, why is this answer accepted?


text:
Arduino UNO HTTPS
Is it possible to call a HTTPS web service on arduino UNO? I am trying to connect it through client.connect(ip,port). It said connected but never respond, ended up in TIMEOUT.

You have some sort of Ethernet or WIFI interface don't you, which one?

ethernet shield

No, it is not possible. The Arduino UNO is not powerful enough to encrypt the data for an SSL connection. On top of that the W5100 chip used on the Ethernet shield has its own IP stack built into it, and that stack doesn't support SSL either.
If you require SSL then it is recommended that you use one of the "dual" boards, like the Yun, and have the Linux portion of the board make the SSL connection for you using cURL.


text:
Steppermotor+Arduino Mega+ Adafruit
I have 2 Stepper Motors (QMot stepper motor1 Amp, 5.3Ohms, 5.3 volts and 200 steps/rev.)
, which are connected to the Adafruit shield2.4, they are mounted to Arduino Mega, the motors pull generally 2 A from external current from Adafruit. My problem is, they don´t rotate smoothly, clearly and fast at the same time.
When I use DOUBLE to define my Stepps, speed is ok but rotation is lout and shaking. When I use MICROSTEP is more smoothly but too much slow. The program is running two stepper motors to roll up optical cables. The cables have to be really precisely come together and accurately be installed on pulley.
Also I need a solution to run my Steppers Motors smoothly, clearly and fast.
Incidentally, I want to know, do I need BigEasyDriver for that?
 If you need more info oder fotos feel free to ask
Regards,
Paria

What's an Adafruit shield2.4? Where is your code?

Adafruit do hundreds of shields. Many of them have multiple versions. WHAT shield is it?!?!

If you have two motors that always need to do the same thing at the same time why are you controlling two motors.  It would be easy to splice [which means join] the two motors control wires together,

adafruit motor shield v 2.3

my motors do diffrent things at the same time. I have to control the speed of second Motor, this motor shakes always according to its duty, that is too bad,  I don´t know how to let it running smoothly and fast. With MICROSTEPS is too slowly and with DOUBLE is shaking...
what should I do?
can I begin with MICROSTEPS and change it into Double and again in MICROSTEPS at the end. Because the Motor have to roll up cabels. The cables have to be really precisely come together, because of that I need Smoothly running, specially at the beginning and at the end....

And your code...? Or do I have to ask you for that ten times as well?

my code is too long, and it is impossible to post it hier !!!! I have tried 10 times...

as an anwser i have postet, if you can read it....

That is not how to do it. I suggest you read the help files and edit your question adding the code properly. Delete your answer. An answer is not the place to add information pertaining to your question.

it is impossible to post it hier - edit the question and post the code. Use code formatting (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

I'd look for a proper stepper driver, e.g. something based on A4988 or similar. I wasted a fair amount of time on the Adafruit motor-shield 2.3 until I finally abandoned it after failing to achieve higher speeds (I also had lots of issues with the motor getting hot). The A4988 takes care of step sequencing including micro-stepping and interfacing and programming is very simple. It only comes in surface-mount packaging but there are bread-board friendly carriers costing a few dollars available from multiple manufacturers.

authors: ชญานนท์ เนตตะพันธ์


text:
Arduino Micro: how to switch off its blue power LED?
everybody!
I have a genuine Arduino Micro ("designed with adafruit", made in Italy) which is working perfectly well.
One thing I'd like to do but cannot figure out how (or at all), is to turn off the blue power LED. I hate blue LEDs, they hurt my eyes, and this one is particularly bright too.
I could just paint it over with black paint but maybe there are programmatic ways to switch it off?
Regards

The Blue LED is permanently connected to +5 volts through R5.
You would have to either remove R5 or the LED from the circuit board.

Unfortunately the blue LED is a direct connection between 5V and GND. You can see below in the schematic exactly how it is connected

The only way to 'turn off' the LED would be to remove either the 1K resistor or LED with a soldering iron.
Another possibility is to take a sharp knife and make a cut in the track directly before or after the LED. I've marked the locations where to cut on the eagle screenshot.

Just gooped the led under black paint, works well enough:)

@AlexeiDolganov that will work, as long as you don't care about the current being consumed by the led. For example in projects running on batteries.

No, it will be connected to USB, no need to count every mA spent.

There is not way to turn it off in software.
The only thing you can do is desolder the led, or it's resistor. Just add some solder to the joints on both sides. Then angle the iron, so it touches both side. The led/resistor will tend to get loose and stick to the iron. Cleanup the board, by removing the excess solder.
I tend to just destroy the led using a utility knife. Just try to lift the "glass" on top of the led with a bit of force. Scrape over the white remains to make sure there isn't any connection left.


text:
When using the IRremote library- why does it say 64 bits when after converting the hex to binary it comes out to be less?
I get this code output on my Serial when the IR receiver gets a signal:
Protocol  : GREE
Code      : 0x01C02350000000E0 (64 Bits)
Mesg Desc.: Model: 1 (YAW1F), Power: Off, Mode: 1 (Cool), Temp: 16C, Fan: 0 (Auto), Turbo: Off, Econo: Off, IFeel: Off, WiFi: Off, XFan: Off, Light: On, Sleep: Off, Swing(V) Mode: Manual, Swing(V): 0 (Last), Swing(H): 0 (Off), Timer: 23:00, Display Temp: 0 (Off)
uint16_t rawData[279] = {...

When I convert 0x01C02350000000E0 to binary, however, it usually comes out to less than 64 bits. I'm assuming it has to do with the parameters of my IR receiver and not normal.

sixteen hexadecimal digits equals 64 binary digits ... that is what fits into eight bytes of data ....... what binary number do you get from 0x01C02350000000E0?

I don't really understand the question. 0x01C02350000000E0 is a 16-digit hexadecimal number and so directly translates to 16x4 = 64 bits. What do you mean that it "usually" comes out as less than that? Do you not count the leading zeroes? They are bits as well.

When I convert 0x01C02350000000E0 to binary, however, it usually comes out to less than 64 bits is like saying when I add 2 plus 2, it usually comes out to 4 .... it either does, or it does not, there is no "usually"

You are confusing the data size and the value size.
Yes, your value can be represented using fewer than 64 bits, but the data size that is used to contain that value is 64 bits in size.
It's like saying that "4" is stored in a 6 digit storage space.  It only needs 1 storage slot, but the allocated space is 6 digits. So what is actually stored would be "000004".
As humans we tend to throw away the leading zeroes because they are meaningless. That's because we are able to use flexible storage sizes in our brains. The computer, though, works on fixed sizes - 8 bit, 16 bit, 32 bit, 64 bit, etc.
You can't store that value in a 32 bit variable, but you can in a 64 bit one. It may be wasteful for that specific value, but it's the smallest size that is available that is big enough.


text:
Is AT command the only way to connect from Arduino to esp2866?
If I am programming an arduino and I wanted to communicate with the internet thru the esp2866 then is AT command the only thing that I can do?
I see a lot of this in the web
void loop() {
 valSensor = getSensorData();
 String getData = "GET /update?api_key="+ API +"&"+ field +"="+String(valSensor);
sendCommand("AT+CIPMUX=1",5,"OK");
 sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
 sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
 esp8266.println(getData);delay(1500);countTrueCommand++;
 sendCommand("AT+CIPCLOSE=0",5,"OK");
}

If I set my Board -> Arduino Uno, I was thinking I can use the following library https://arduino-esp8266.readthedocs.io/en/2.7.4_a/esp8266wifi/readme.html
#include <ESP8266WiFi.h>

const char* ssid     = "my-ssid";
const char* password = "my-password";

void setup() {
  Serial.begin(115200);
  // We start by connecting to a WiFi network

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

  WiFi.begin(ssid, password);

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

But I am getting
exit status 1
ESP8266WiFi.h: No such file or directory

Looks like the following library is only available when you set the Board-> Generic ESP8266 Module and is only used when you want to program the ESP8266 in the Arduino IDE?  Is this correct?
So in my question, does it mean that to communicate from the Arduino into the internet, I will be sending the AT command and communicate thru the SoftwareSerial.h?

you could use a library which has a nice standard Arduino networking interface over the AT commands. The WiFiEsp library for old AT firmware or my WiFiEspAT for AT 1.7+ https://github.com/jandrassy/WiFiEspAT

is AT command the only thing that I can do?

No. The AT commands are provided by the AT command firmware. You can replace that firmware with whatever you want.
It is common to write your own software for the ESP8266 to do your communication for you and communicate with other devices (including an Arduino) in whatever way is suitable.
Many times you don't even need the Arduino any more as the ESP8266 can do everything (it struggles with analog signals as there is only one rather inferior ADC pin).

Looks like the following library is only available when you set the Board-> Generic ESP8266 Module and is only used when you want to program the ESP8266 in the Arduino IDE? Is this correct?

That is correct. That is for when you are writing your own ESP8266 firmware to replace the AT firmware.

So in my question, does it mean that to communicate from the Arduino into the internet, I will be sending the AT command and communicate thru the SoftwareSerial.h?

Only if you retain the AT firmware on the ESP8266. To be honest that firmware is terrible and all the tutorials are bad. You should at the first available opportunity learn to program the ESP8266 directly and maybe retire the Arduino unless you need to use it as a glorified IO expander.

Thank you very much.  Yes this is where I am very much confused.  I see a lot of google search results like this https://www.instructables.com/id/Using-ESP-01-and-Arduino-UNO/.  and it looks like it is passing only AT commands into the ESP2866.  I am studying this for now so I cannot remove the Arduino in the equation.  But to satisfy my curiosity, if I don't replace the AT firmware then I could only use AT commands right?

Also another question please, I followed the following link https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide and I was able to make it work but my ESP8266  is not from Adafruit.  I noticed that after doing so, the AT commands stop working.  Does it mean that my firmware now is that of the https://arduino-esp8266.readthedocs.io/en/2.7.4_a/esp8266wifi/readme.html?  I am a bit confused on this parts.  I set my ESP board in bootload mode and then uploaded the blink.  After that my AT commands stop working when I used the serial monitor.

The AT firmware only responds to AT commands. That 's what it is and what it does. If you want to use anything other than AT commands then you will have to replace the AT firmware with firmware that responds to the commands you want to send.

Yes, you replaced the AT firmware with your own (adafruit's) custom firmware. You have successfully directly programmed the ESP8266.

Ohh okay so that is why it is not responding to my AT commands anymore.  Just one last thing please.  If I retain my current setup with an Arduino and the custom firmware from the https://arduino-esp8266.readthedocs.io/en/2.7.4_a/esp8266wifi/readme.html in my ESP 8266.  Then how can I connect thru the internet from my Arduino code since AT command is not available anymore.  I could not find any google links to do this.  I always see AT commands.  I spent 2 days reading on this subject for my project.  Thank you very much for your time.

You write your own software for the ESP8266 that accepts commands through serial (which you define) and does things according to those commands.

Oooohh okay... so the logic goes like this.  I program a series of functions in my ESP-8266 like connectToWifi() and in my loop() function I watched for messages from Serial.  What ever messages I received from serial corresponds to the function that I will be calling.  I then burn those program in my ESP.  I go back to Arduino, set the Board to Arduino Uno and in my loop, I will be sending a mesage serially like connectToWifi() and my ESP will received this and call the corresponding function and return it back to the Arduino Uno serially also.  Is this the pattern?

I spent two days already on this and I really don't like the examples in using the AT command.  However there is no documentation that I have seen or I might not be typing the correct search keys that would discuss the logic of defining your custom commands.

Yep, that's the idea.  I have an ESP8266 sketch specifically for MQTT that does that kind of thing: https://github.com/MajenkoProjects/MQTTGateway

The point of defining your own custom commands is they are your commands. You define them how you want to define them and handle them how you want to handle them. They're just bytes arriving over serial.

This is really sweet mate.  I learned so much from you by just several minutes compare to the countless hours I have tried the past two days by trying all those AT commands that I don't like actually.  Thank you very much mate

https://imgflip.com/i/4cihtl ;)

Just out of curiosity, why have I not found any google hits from what you have laid out.  This could really help lots of beginning programmer.  From my perspective as a beginner, I was under the impression that the ESP8266 is just like any normal components with a library that you can call and add to your arduino with a defined API and not those quirky AT commands.  Anyhow than you very much again.

There is the basic assumption that you know the ESP8266 is just a microcontroller that is running firmware that exposes AT commands. Unless you already know that then googling for information is not easy.


text:
Confuse about PROGMEM and R"====()===="
I saw the following code from https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ but I could not understand it thoroughly...
I looked at the documentation of PROGMEM from this https://www.arduino.cc/reference/en/language/variables/utilities/progmem/ but could not understand the importance in the code on why you should put your variables in flash memory instead of SRAM (the usual memory?)?
const char MAIN_page[] PROGMEM = R"=====(
  <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

  circuits4you.com

)=====";

Also, I could not understand the definition of R"====()====", what is meant by this in arduino?

why you should put your variables in flash memory instead of SRAM

Because the Arduino has only a very small amount of memory. If you have data that will never change it's better to store it in flash (of which there is much more) so as to leave the SRAM free for data that does change.

Also, I could not understand the definition of R"====()====", what is meant by this in arduino?

The R means "Treat everything between these delimiters as a raw string".  That is, everything between "=====( and )=====". It's not an Arduino thing, but a general C++ thing (see here). The ===== can be anything you like (within certain bounds) as long as it's the same at both the start and end of the string.  So you could use R"-=(This is "text")=-" which would assign the string This is "text". It's a great way of working with long strings that may want to contain " as otherwise you would have to escape each and every " as \". So the string I showed just now would otherwise have to be written as: "This is \"text\"", which can get very messy if there are lots of " in there.  The important thing to remember is that )===== mustn't appear in your text anywhere, so make sure it's something really obscure.

Thank you very much for being patient in helping beginners!

This applies to older AVR architectures. Newer one (for example ATMega4809) are mapping flash and the other memories into data space and there is no need for using PROGMEM. The same applies to ARM architecture - there is no PROGMEM, as there is no need to copy const variables into RAM to be accessible directly.

In your example, wouldn't R"-=(This is "text")=-" actually need to be R"-=(This is "text")-="? Or am I not understanding it right? It's almost like the HEREDOC syntax right?


text:
No SPIFFS only OTA in NodeMCU ESP8266
I have a NodeMCU ESP8266  ESP-12E and I tried uploading a file thru the SPIFFS.  I am not sure why I see OTA instead of the SPIFFS?

Is there a configuration that I missed?

https://www.instructables.com/Using-ESP8266-SPIFFS/?amp_page=true not sure but check this . It may not help

maximum application size is less then 1 MB. so there is no other use for the rest of the flash then FS. for board you selected there is no predefined partitioning without OTA. what is your question?

In this link https://cdn.instructables.com/ORIG/FST/OP12/IZT6TEBJ/FSTOP12IZT6TEBJ.png?auto=webp&frame=1&width=1024&fit=bounds&md=f16daccb8697a6bd8728838feb18d9de it is showing SPIFFS but in my Arduino IDE it is showing OTA?  Why is this so? That is my question

Yes please refer to my answer and that is because he is using an older version of the package and arduino

SPIFFS (SPI Flash File System)  is also know as FS(File system) . so What you are seeing as FS is basically SPIFFS .The OTA partition on esp8266 is compulsory so you cant get rid of it .
Hope this helps

Ohh Okay so that is how it is.. Thank you then!

and why is there in Tools menu FS and not SPIFFS as n the mentioned instructable?

Sorry don't understand what you are asking

the question was that the menu doesn't  show SPIFFS but FS and OTA. a good answer should contain why it is so.


text:
When Writing Library, return String or return char *
I am trying to write my own Arduino library and I would like to make it useful not just for ESP32/ESP8266 boards but also with Arduino boards.
I have created my header file like this

test.cpp

#ifndef TEST
#define TEST
#include "Arduino.h"

#define MAX_STRING_LEN 50

class MyClass{
    private:

    public:
        String getString();
        char * getCharPointer();
        char * getAnotherCharPointer();
};

#endif

and my

test.cpp

#include "test.h"

static char buffer[MAX_STRING_LEN+1];

String MyClass::getString(){
    // Sample REST API call
    String testString = String("{\"test:\" \"hello String json\"}");

    return testString;
}

char * MyClass::getCharPointer(){
    // Sample REST API call
    const char * sample_json = "{\"test:\" \"hello Char Pointer json\"}";
    strcpy(buffer, sample_json);
    return buffer;
}

char * MyClass::getAnotherCharPointer(){
    // Sample REST API call
    const char * sample_json = "{\"test:\" \"hello Another Char Pointer json\"}";
    strcpy(buffer, sample_json);
    return buffer;
}

My test file main.cpp

main.cpp

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

MyClass myClass;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  Serial.println(myClass.getString());
  Serial.println(myClass.getCharPointer());
  Serial.println(myClass.getAnotherCharPointer());
}

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

Result is ok
{"test:" "hello String json"}
{"test:" "hello Char Pointer json"}
{"test:" "hello Another Char Pointer json"}

I have these doubts that I would like to ask for suggestions.

Is returning the String class in Header files, not a good idea?  For ESP32/ESP8266 they are okay as they have big memory but for Arduino Uno boards I see a lot of discussions about not using String because it is bad and causes memory fragmentation etc.
Is returning char * the safest way to make it compatible and useful to all MCU boards?
Next question in char pointer, I often see this pattern done when returning char pointers like in this Time.cpp wherein a static buffer is used and defined at the implementation file (test.cpp) and all functions(getCharPointer, getAnotherCharPointer) that needs to return a char pointer just manipulates the static char buffer by using strcpy.  Is this the proper way to go in Arduino programming?

Can somebody please clear my doubts?  Thank you.

Good question! I am afraid it may be a bit opinion based though. I like the static buffer approach for its memory friendliness. It is, however, dangerous unless the library user is well aware of its implications. Not sure it's suitable for beginners...

If all your functions do is to return a string literal, then just use the string literal directly, those functions are not necessary. The pattern you sited do that because the string literals are stored in the flash memory (PROGMEM) and therefore need to be copy-out into RAM, this however depends on your chip architecture, you need copy-out from FLASH to RAM for classic AVR chips (like ATmega328), however it doesn't required for ARM chips, ESP or even modern AVR chips released since 2016...

@hcheung: I believe those string literals are here only to provide simple dummy examples, and the actual library is going to build the strings from data gathered at run time.

[The OP asks:] For ESP32/ESP8266 they are okay as they have big memory but for Arduino Uno boards I see a lot of discussions about not using String because it is bad and causes memory fragmentation etc.

On Unos and other boards with very low memory, fragmentation won't take very long to happen. On boards with larger memories, it will merely take longer! but it will happen; it's just a difference of when. (And for completeness, I should say that allocating a few objects, once, and within the device's available free memory, won't cause fragmentation, any more than static allocation would).

So why is allocation/deallocation used at all [I ask, rhetorically...]?

On systems running a full OS, driven by ourselves with a keyboard and mouse, most application programs are transient - they start up, do a job, and exit; even longer running ones like office applications are fairly speed-limited by us slow humans. And if a program crashes, we're still sitting there to re-run it, and no external device gets left hanging for hours or days, maybe destroying itself (by overheating, perhaps), maybe injuring or killing a patient (in the case of a medical device), injuring or killing many people (in case of a vehicle's engine- or flight controls).
Otherwise, run-time memory allocation is a convenience for the programmer.

So what to do in an embedded system, instead [asks I]?

I use two techniques to get around the crash-proneness of the compiler-libraries' allocator/deallocators:

When I write a library, I design it to expect an (object *) from the caller, as you anticipated in your 'doubt #3'. All the library has to do is put its result there; the memory will already have been allocated. The library doesn't need to know or care how it was allocated. Does this sound like I'm avoiding solving the problem and leaving memory issues for some else to deal with? Yes, indeed, and it is deliberate! The user of my library - you, (or me, some other day), the application writer/system architect - is the best one to anticipate their particular system's memory needs, and to decide how best to meet them.Writing my library this way lets the library-user decide whether a static buffer, a local one, or a dynamic allocation is the best fit for their application.

I write my own memory management (probably at the application level rather than in the library). This almost always takes the form of an array of fixed-length buffers. No matter how much memory the caller asks for, as long as it is less than that fixed size, and one is available, then the call succeeds and a buffer will be returned; otherwise, the call fails. The caller doesn't know, or need to know, that the buffer returned to them might be larger than they requested.Why is this technique any better? malloc()/free() and new()/delete() break up free memory into ever smaller pieces, as they are requested. A fixed-size-buffer allocater does not break up memory.

A system using these techniques together avoids memory fragmentation. The only way such a system can fail (due to memory allocation) is to not have enough in the first place, and the only fixes are 1) for the programmer to assign more memory for fixed-size buffers; or, if the board doesn't have enough more, then 2) build the system with a host board that has enough memory.

I often see this pattern done when returning char pointers like in this Time.cpp wherein a static buffer is used and defined at the implementation file (test.cpp) and all functions(getCharPointer, getAnotherCharPointer) that needs to return a char pointer just manipulates the static char buffer by using strcpy. Is this the proper way to go in Arduino programming?

Arduino programming is C++ programming. You can return a pointer to a static buffer, of course. But the user of your function needs to know that if they call the function a second time the data will be overwritten. So, they would need to strcpy (that is, copy) the data before it is overwritten.
Personally I would stay away from the String class, unless it is being used only occasionally. It is fine with strings that are always the same size, but if they are not, memory fragmentation will be an issue.


text:
Arduino Micro Breadboard USB Not Connecting
I have been working on getting an Atmega32u4 connected to USB. I lifted the connections from the Arduino Micro schematic for the preliminary schematic shown here. When I connect the chip to USB, the system (Ubuntu 18.04) does not appear to recognize it.
I was able to burn the Caterina-Micro bootloader via my Pololu USB AVR Programmer as well as through ArduinoISP to confirm that everything was uploaded correctly. The following is the output of avrdude using the pololu programmer:

$ avrdude -p m32u4 -P /dev/ttyACM0 -c avrispv2 -U flash:w:Caterina-Micro.hex
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100%
0.00s
avrdude: Device signature = 0x1e9587 (probably m32u4) avrdude: NOTE:
"flash" memory has been specified, an erase cycle will be performed
To disable this feature, specify the -D option. avrdude: erasing chip avrdude: reading input file "Caterina-Micro.hex" avrdude:
input file Caterina-Micro.hex auto detected as Intel Hex avrdude:
writing flash (32730 bytes):
Writing | ################################################## | 100%
8.21s
avrdude: 32730 bytes of flash written avrdude: verifying flash memory
against Caterina-Micro.hex: avrdude: load data flash data from input
file Caterina-Micro.hex: avrdude: input file Caterina-Micro.hex auto
detected as Intel Hex avrdude: input file Caterina-Micro.hex contains
32730 bytes avrdude: reading on-chip flash data:
Reading | ################################################## | 100%
6.76s
avrdude: verifying ... avrdude: 32730 bytes of flash verified
avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)
avrdude done.  Thank you.

Using a Saleae Logic Analyzer, I sniffed the following USB communications. It seems to me that the atmega is transmitting properly but not receiving any responses but I am not certain.
I confirmed that the USB cable in use was working by plugging it into an Arduino Micro that I have. System was able to identify Arduino Micro, Arduino Uno and pololu AVRisp.
I am hoping that there is an easily assignable cause to the issues that I am experiencing. If any addition information is required, please ask.

Your title mentions breadboard... how exactly are you building this circuit?

Sorry for being vague on the build. Please find an image of the breadboard (https://www.dropbox.com/s/ljlww8ytaqym3ve/IMG_20200825_123859.jpg?dl=0). A sparkfun 44TQFP breakout was used for the atmega32u4.

Ok. I thought it might be. A breadboard is not a conducive environment for usb. The timing has to be precise and the capacitance of the breadboard is probably skewing your crystal frequency.

Also you should check dmesg for errors when you plug the USB in.

Thank you for your suggestions and solutions. The following is the output of 'dmesg | grep -i usb' after plugging in the board:
[1735217.833561] usb 2-1-port2: attempt power cycle
[1735218.437472] usb 2-1.2: new full-speed USB device number 71 using ehci-pci
[1735218.853479] usb 2-1.2: device not accepting address 71, error -32
[1735218.933476] usb 2-1.2: new full-speed USB device number 72 using ehci-pci
[1735219.349481] usb 2-1.2: device not accepting address 72, error -32
[1735219.349551] usb 2-1-port2: unable to enumerate USB device

Taking capacitance between the crystal and the microcontroller as the most likely issue causing my USB problems, is there a way that the internal oscillator can be used for USB (low speed or high speed)?

No. The internal oscillator is not accurate enough. You need to have the crystal and its capacitors mounted direct on the PCB with the chip. This is why people use the small development boards when working with breadboards.


text:
help explain pulseIn function with arduino and Ultrasonic sensor
dears Engineers.. i got stuck with this issue couldn't understand.. please help with explanations.
first i was upset of my ultrasonic sensor reading deviations, that is i examine my sensor indoor and at quite environment,, so what makes this noisy output readings??!!!
so i tried to dig into the pulseIn function and tracking the timing of each instruction in the code..
after reading the library.., i decided to use pulseInLong function.
following is a result of some iterations timing in microseconds:
Ultrasonic Sensor HC-SR04 Test
with Arduino UNO R3
Start ~ trig LOW  ~ 10us delay ~ trig High ~ 10us delay~ trig High ~   pulseIn    ~   Duration
0           8           12          8           12          4           7352            137976
4           4           12          8           12          8           7336            137960
4           8           12          8           12          8           7352            137976
4           8           12          8           12          8           7356            137980
4           8           12          8           12          8           7352            137976
4           8           12          8           12          8           7356            137980
4           8           12          8           12          8           7360            137984
4           8           12          8           12          8           7364            137996
0           8           12          8           12          8           7364            137992
4           8           12          8           12          8           7372            137996
4           8           12          4           12          8           7380            138004
0           4           12          8           12          8           7372            137996
0           4           12          8           12          8           7348            137968
4           8           12          4           12          8           7372            137996
4           8           12          8           12          4           7376            138004
4           8           12          8           12          8           7380            138008
0           8           12          8           8           8           7352            137980
4           8           12          4           12          8           7352            137976
4           8           12          4           12          8           7368            137992
4           8           12          8           12          8           7340            137964
4           8           12          4           12          8           7352            137980
4           8           12          4           12          8           7360            137984
12          8           12          8           12          8           7368            137996
4           8           12          8           12          8           7348            137972
4           8           12          8           12          12          7360            137984
0           8           12          8           12          8           7344            137968
4           8           12          8           12          8           7352            137976
4           8           12          8           12          8           7364            137988
4           8           12          4           12          8           7360            137984
4           8           12          8           12          4           7372            138000

first i wondered why there are different execution time for the same instruction??!
for example digitalWrite(trig_pin,LOW or High) varies in range 4 ~ 12 microseconds!!????
more strange when i found elapsed time after delay 10us, micros() function shows only 8 us??!!!
all these in range of 16 us,, so i expected maybe due to some instruction cycles or unprecise clock...etc.
but the BigBang i shocked when read this huuuuuge difference in pulseIn timing measurment;
i reset the timer befor the function and just after it, so i got an elapsed time in range of 7350 us. in the same time the resultant measured time from the function in range of the  138000 us?????!!!!!!
put in mind that pulseInLong is a blocking function..as you will see below, it loops in a while loop until timeout (so return 0) or pulse generated and measured before timeout then return pulse elapsed time.
first i suspected in this number maybe not microseconds. inspected the function deeply, ??!!!
i found it using the exact micros() function such i do in the code?
 * this function relies on micros() so cannot be used in noInterrupt() context
 */
unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout)
{
    // cache the port and bit of the pin in order to speed up the
    // pulse width measuring loop and achieve finer resolution.  calling
    // digitalRead() instead yields much coarser resolution.
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    uint8_t stateMask = (state ? bit : 0);

    unsigned long startMicros = micros();

    // wait for any previous pulse to end
    while ((*portInputRegister(port) & bit) == stateMask) {
        if (micros() - startMicros > timeout)
            return 0;
    }

    // wait for the pulse to start
    while ((*portInputRegister(port) & bit) != stateMask) {
        if (micros() - startMicros > timeout)
            return 0;
    }

    unsigned long start = micros();
    // wait for the pulse to stop
    while ((*portInputRegister(port) & bit) == stateMask) {
        if (micros() - startMicros > timeout)
            return 0;
    }
    return micros() - start;
}

anyway..i dont want to make this story long..
can someone explain what is going on to me please?!
thanx
here is arduino code i used
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

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

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed

  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");
  Serial.println("Start ~ trig LOW   ~   10us delay   ~   trig High   ~   10us delay   ~   trig High    ~    pulseIn    ~   Duration");

}

void loop() {
  // put your main code here, to run repeatedly:
  // Clears the trigPin condition
  int indx = 0;
  int arr[7] = {0};
  double last = micros();

  arr[indx] = micros() - last;
  indx++;
  last = micros();

  digitalWrite(trigPin, LOW);

  arr[indx] = micros() - last;
  indx++;
  last = micros();

  delayMicroseconds(10);

  arr[indx] = micros() - last;
  indx++;
  last = micros();
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds

  digitalWrite(trigPin, HIGH);
  arr[indx] = micros() - last;
  indx++;
  last = micros();

  delayMicroseconds(10);
  arr[indx] = micros() - last;
  indx++;
  last = micros();

  digitalWrite(trigPin, LOW);
  arr[indx] = micros() - last;
  indx++;
  last = micros();

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseInLong(echoPin, HIGH);
  arr[indx] = micros() - last;

  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor

  for (int i = 0; i <= indx; i++)
  {
    Serial.print(arr[i]);
    Serial.print("     \t    ");
  }
  Serial.print(duration);
  Serial.println();

}

Look at the source code, you have it.  digitalWrite is a function that has several lines in it.  There are interrupts running on the chip.  If one of those interrupts fires during the execution of the digitalWrite function then it will take longer to execute that time.

This method of reading an ultrasonic sensor is a great way to introduce someone to how those types of sensors work, because it is really easy to follow code, but there are much better ways to handle reading an ultrasonic sensor in a much more accurate manner.

thanx Delta_G for responding here,
but unfortunately, i still can't get the point!!!
first: why sometimes i measure an elapsed time 8us, while i used a delay of 10us?!
second: why do i receive big difference in time measurement between elapsed time while execution the pulseInLong function and its return duration measurement!?

Go read the documentation on delayMicroseconds.  It clearly states that the resolution of that function is 4us.

Just to add my two cents. Perhaps the digitalWriteFast library might come handy for this time-critical application. I normally use it instead of the default function and it certainly saves a bit of time

I see at least three reasons for the behavior you notice:

micros() has a resolution of 4 µs. If you could call it at a
period fixed to exactly 10 µs, you would see the time deltas
alternate between 8 and 12 µs. But then micros() takes some
time to execute, so if you use it to time a function that takes
10 µs to execute, you will read 12 µs more often than 8.
There is a timer interrupt firing every 1024 µs. Any process
that gets interrupted will show an execution time longer than normal.
This is the likely cause of digitalWrite() taking occasionally a
lot longer than usual.
pulseIn() waits for the start of the pulse before it starts to
measure its duration. Its execution time can then be significantly
longer than the pulse duration it reports.

i expected maybe due to some instruction cycles or unprecise clock.

The same clock is used for sequencing the CPU instructions and for
timing them. So the clock precision has no effect on the timings you
measure.
Edit: There is an extra issue here, which is the overflow of
arr[6]. The execution time of pulseInLong() may be something like
138,424 µs. Since an int on the Uno is 16 bits, this value wraps
modulo 216 to 7,352, which is the value shown in the first
line of the output.

Dear @Edger Bonet and other Engineeries
please concentrate with me little bit..

@absi: What do you mean?

#3) The point number 3: regarding pulseInLong returned time and execution time:
the time returned by the function is what i listed in the timing table under duration, where the execution time is listed under pulseIn at the timing table.
as you can see the execution time is much less than the returned measured time for the pulse, and that is very strange??!!
so please someone try to explain

@absi: Oh, I missed that. See amended answer.

Why do I receive the big difference in time measurement between
elapsed time while execution the pulseInLong function and its return
duration measurement?

The answer lies in the choice of the way it is implemented.
The delay function itself is helpful but the accuracy is not great when precision is needed. Here is the official note from the site:

This function works very accurately in the range of 3 microseconds
and up. We cannot assure that delayMicroseconds will perform
precisely for smaller delay-times.
As of Arduino 0018, delayMicroseconds() no longer disables
interrupts

If you want to really be precise, I recommend to use hardware timers. I believe it will suffice. to know more about using hardware timers you can refer to
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers
https://maker.pro/arduino/projects/timer-interrupts-improve-your-arduino-programming-skills


text:
Error "cstddef: No such file or directory" on use AzureIoTHub
Good Morning
I'm trying to integrate with Azure IoT with Arduino Mega 2560.
I imported the AzureIoTHub and AzureIoTUtility lib.
I just created this part of the code
 #include <AzureIoTHub.h>

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

}

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

}

however, when I compile, I get the following error message.

In file included from
C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/azure_c_shared_utility/platform.h:7:0,
from C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/AzureIoTUtility.h:7,
from C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTHub\src/AzureIoTHub.h:7,
from D:\Documents\Dev\Pocos\Arduino\ArduinoSolution\ArduinoSolution.ino\WiFiPoco\RoboCore\azureHub\azureHub.ino:3:
C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/azure_c_shared_utility/strings.h:8:10:
fatal error: cstddef: No such file or directory  #include

I imported ArduinoStl and the problem continued.
what am i doing wrong in this case?
thanks

Did you happen to read the (very short) list of supported hardware in the README of the Azure IoT library? It is only for ESP8266 and ESP32 (and then only specific ones by the look of it).

Azure IoT is only supported on ESP8266 and ESP32. As stated in the README for the library:

Currently supported hardware:

ESP8266 based boards with esp8266/arduino

SparkFun Thing

Adafruit Feather Huzzah

ESP32 based boards with espressif/arduino-esp32

Adafruit HUZZAH32


text:
L298N motor driver and battery issues
I'm trying to build an Arduino 4WD smart car. so i connected my l298N motor driver module with my v4 shield and used a 4 x 1.5v AA batteries to try and power my 4 motors up. i connected 2 of the motors in parallel so i can use 1 L298N to power it on. initially it worked but then a few minutes later it stopped moving. i thought my connections were bad so i redid all the connections but it didn't work so i changed the battery to 9v. with this the motors worked for a few seconds then stopped but was making noise so i tried powering the motor driver with my Arduino but it didn't come on. I tried powering the motor driver module with my Arduino but the driver module didn't come on.i decided to use my bread board and l293D IC to control my motors it didn't work but the motors were making noise. I changed my motor to one that i removed from a PlayStation controller but nothing still.i did research on the internet and was advised on this tutorial (https://create.arduino.cc/projecthub/maxxlife/arduino-4wd-car-cf5fd0) to not use AA batteries but no explanation why. so i checked other tutorials and saw people using AA to control 1 or 2 motors. Why shouldn't i use AA batteries? does anyone please think they know the solution to my problem? thank you
This is how my kit looks https://www.ebay.com/itm/NEW-4WD-Robot-Smart-Car-Chassis-Kits-car-with-Speed-Encoder-for-Arduino-M26/201561877173?_trksid=p2047675.c100009.m1982&_trkparms=aid%3D777000%26algo%3DABA.MBE%26ao%3D1%26asc%3D36860%26meid%3Dc76077722d4348e88152fa6c7f32c005%26pid%3D100009%26rk%3D1%26rkt%3D1%26sd%3D181329341315
Also should i change my use Li-ion battery 18650 x2 instead of the 6LR61 9v battery i used

go back to the begining ... one motor, 4 AA cells, simple sketch that runs the motor in one direction for 1 second, stops motor for one second and repeats

I tried that but it didn't work so i checked the voltage reading of the AA and i got around 5v. i tried my 9v battery but i checked the voltage reading first and it was 7v. the motors worked for a while but now have stopped working i checked the voltage readings and i'm getting 4v

I have the same problem. I made car from this link: https://www.electronicshub.org/bluetooth-controlled-robot-using-arduino/ currently, I used 4 AA batteries for this project but 4 dc motors not working. After that, I trying with a 3.7 V lion battery (2200mAH) with MT3608 step-up convertor to set 10V output which given to Arduino and L298N module to drive the motors but suddenly discharge the battery. So how to solve this issue?? Thanks in advance. Chirag

Rule #1 9V batteries a power supply they are NOT. In your case you are looking at small voltages for the motor power. Your choice of a driver is not the best as you will have from 1.2 to 2.4 volts across the L298 depending on the loading. This is directly from the ST data sheet. Try the TB6612FNG instead, taking advantage of the device’s use of MOSFETs. The TB6612 may be a little more expensive, but it will be clearly worth it.

Thank you for your answer but i don't really get what you're saying. i know the L298N is not really a good choice but i don't really have an option on what motor driver to use because of where i live. I did some research on the web and i think my problem is the batteries I'm using. i think the 9v and AA batteries cannot supply enough current for the 4 motors but I'm not sure. what do you think?

I agree. Batteries have a discharge curve which shows how much you can get out of them with a given load. Overloading them causes them to lose capacity.

I changed my batteries to 2 18650 li ion batteries and now the driver works well. But can you please explain  how i can calculate what battery is best to use. thank you for your help so far

You are welcome. That I cannot do, I do not know your resources, what the final design is like, how many you are going to make, what the actual load is, what the efficiency of your system etc.. That decision you have to make and rest assured there will always be a better one but there are also a whole bunch that are not as good. You are the design engineer you get to make the choice you will be happy with.

I give you credit for trying. In your spare time read some materials on basic
electronics. I will see if I can help but no guarantee. he motor driver you are using
has transistors as the driving element. That indicates the motor power is going
through them. Since they are transistors they have a PN junction. When voltage goes
through a silicone junction it will drop 0.7volts for each junction. If lightly
loaded sometimes less. Note: this loss is expelled as heat. You have two configured as a darlington configuration on each output. This places two junctions in series with each motor lead.  That is a total of 4 junctions yielding a drop of 4 * 0.7 = 2.8 Volts.  Subtract that from your supply before you start, that is a big hit in low voltage systems. The MOSFET will have a drop of about 0.05Volts on each side leaving you 2.7 more volts to work with. Batteries have power ratings, these are conservative:
Type Cap (mAh))  Drain(mA) -
D    13000      200 -
C     6000      100 -
AA    2400       50 -
AAA   1000       10 -
N     650        10 -
9     500        15 -
The battery capacity will be better with lower drain currents and shorter with higher drain current. To determine your battery life, divide the capacity by the actual load current to get the hours of life. For example: A circuit that draws 10 ma powered by a 9 volt rectangular battery will operate about 50 hours: 500 mAh /10 mA = 50 hours The cell voltage of alkaline cells steadily drops with usage from 1.54 volts to about 1 volt when discharged. The voltage is near 1.25 volts at the 50% discharge point. Alkaline cells exhibit a slightly increased capacity when warmed and the capacity drops significantly at temperatures below freezing. Mercury and silver oxide batteries have nearly twice the capacity as alkaline batteries of the same size but the current ratings are significantly lower. Alkaline batteries also have good shelf life making them ideal for home-made electronic projects. Rechargeable batteries have less capacity than primary cells Look at it like the batteries are your piggy bank. The more your take out the less you will have. The faster you take it out the quicker you are out of money.

ok thank you. but i still don't really get this.is drain how much current it can produce? if no then. According to the info i found on the internet the dc motors take 100mA at 5v. since 9v batteries have a type cap of 500mAh then shouldn't my motors last at least 5hrs or this is wrong because the drain is 15mA so i should use a type D or C battery. Also if i connect 4 AA in series does this increase the drain. i also connected the 9v battery and 4 AA in series and the motor came on and rotated faster and longer than using 9v alone i know this is part due to the increased voltage

But does the drain of the batteries also increase to 215mA? Li-ion have a capacity of 2200mAh so if i use 2 for my 4 motors then it should last more than 5hrs (2200/400) so doesn't that mean Li-ion or Lipo is my best bet?

The tork of your motor is dependent on watts. Since it is a fixed resistance the higher the voltage the more tork you will get. Also since Ohm's law entered into this the higher the voltage the higher the current the more watts you get hence more tork. More current decreases battery life at the expense of more tork. Drain as referred to is the load on the battery or the amount of energy it is draining from the battery.


text:
Avr dude programmer
I was trying to upload a hex file to my attiny85 with an arduino,and I came across this:
avrdude -c avrisp (followed by other codes and the flash address )

This doesn't work and it gave one of the most famous arduino errors : stk500_getsync() : not in sync: resp=0x00
Then I tried
   avrdude -c arduino

And the code was successfully downloaded, but the chip itself doesn't work as intended. So this is the question, what does the -c [programmer id] actually do, for example in this case, does it download the hex file to my arduino?
Thanks in advance.

DId you disable the reset on the Arduino after installing the ArduinoISP sketch? If not, then you just reprogrammed the Arduino with your ATTiny85 program.

@Majenko disable with capacitor at the reset? I just tried and same error code with avrisp.(Also I don't know if I actually prevented the reset or not, no way I know now.) So the arduino option programs the arduino regardless of what chip I choose later ?

The -c selects which protocol to use to talk to the remote device. -c arduino selects the Arduino's bootloader as the protocol to use. -c avrisp selects the protocol spoken by the ArduinoISP sketch.

Did you reprogram the ArduinoISP sketch back on the Arduino after breaking it with -c arduino and before testing it again with the reset disabled?

@Majenko the one in the example , yes. I also reburned the bootloader for the attiny85 just in case . Since the data flows from my laptop through the arduino then into the attiny85, does this mean that by selecting -c arduino will download the hex file into the arduino, or download the hex file into the attiny85 with arduino protocol ?

It sounds like you're not actually doing what you describe (and we assume from the situation) you are doing. Using an Arduino to program an ATTiny85 usually means using it as an ISP to flash the chip directly. Instead it sounds like you are actually using a bootloader on the ATTiny and using the Arduino as a dumb UART interface. Is that correct?

@Majenko that... Actually sounds like it. All I want is to download my hex file into my attiny85 , and I do not have any other way of connecting the attiny85 to my laptop.

Yet you seem to have the ability to program the bootloader on the ATTiny? Why not just program the HEX file directly using the same method instead of messing with bootloaders?

@Majenko I burned the bootloader with the arduino software.(under the tools) I really do not have the ability to properly program an avr device now. And I think I'm not actually burning the bootloader although it says so, as I saw from other forums that I am just actually resetting the clock rate of the chip.

@Majenko I couldn't use "avrisp" because of the error, and "arduino" doesn't seem to work.

Using an Arduino to program a microcontroller is very crude at best. You should invest in a USBASP from eBay. They're dirt cheap.

Which bootloader do you think you are installing on the ATTiny?

@Majenko because of where I live, it's not that easy to obtain these products, eBay included. And this is my one time project, and I won't be returning to avr devices anytime soon (I think).

@Majenko bootloader wise..... I have no idea. Attiny85 comes with a bootloader...Right?

You have no idea what bootloader you tried installing? Where did you get it?

@Majenko here http://my.element14.com/microchip/attiny85-20pu/mcu-8bit-attiny-20mhz-dip-8/dp/1455162?CMP=i-55c5-00001621

No, I mean the bootloader. Where did you get the bootloader? I also reburned the bootloader for the attiny85 just in case

@Majenko the "burn bootloader" under the "tools" in the arduino ide. Which most likely isn't a bootloader.

Try these steps:

Install ArduinoISP (in the examples menu) on your Arduino board.
Disable reset on the Arduino board by adding a 10µF capacitor between the RESET and GND pins.
Wire the ATTiny chip to the Arduino following this schematic.
Run the upload command using -c avrisp with your program's HEX file

Alternatively you can just install the boards package detailed in the schematic link and program it directly from the Arduino IDE instead of messing with the avrdude upload command.
You must also ensure that you are uploading at the right baud rate. The ArduinoISP sketch defaults to 19200 baud:
// Configure the baud rate:

#define BAUDRATE    19200
// #define BAUDRATE 115200
// #define BAUDRATE 1000000

and you must match that in your avrdude command with, for example, -b 19200.

C:\Users\User>avrdude -c avrisp -P com1 -p t85 -Uflash:w:C:\Users\User\Desktop\sd8p_mo.hex:i
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude done.  Thank you. (exact code and error returned. also using 22uF capacitor, other forum said it was okay)

I would suggest you forget using the command line for this. Follow the tutorial I linked to step by step and use the IDE for everything.

Oh, and is your Arduino really on COM1?

it is. I changed it in the device manager and made sure of it in the arduino ide. The code I want to import is found in hex.(http://elm-chan.org/works/sd8p/report.html), and the tutorial only allows ide, if im right.

There is source there, just not for the Arduino IDE (or not easily).

Add -b 19200 to the avrdude command.

You can also try -c arduinoisp

Another one to try is -c stk500v1. It's really confusing - they have "ArduinoISP", "ArduinoISPOrg" and "ArduinoAsISP" - all to do the same thing and all slightly different. I guess for different versions of the ArduinoISP code.

HOLY It worked!!! the "-b 19200"!!!! Thank you so much !!!! I know what it means (baudrate right), but why?

The baud rate has to match the baud rate programmed in the ArduinoISP sketch. That defaults to 19200, but avrdude defaults to 115200.

Let us continue this discussion in chat.


text:
What does an arduino sketch translate to before compilation?
I've been experimenting with Arduino on both esp8266 and AVR chips. The structure of the .ino file usually looks like this:
#include "Arduino.h"
#include "ESP8266WiFi.h"
##Some includes

void setup()
{
...
##Will be only run once at the begining.
}

void loop()
{
##Runs this code in a constant loop
}

My assumption is that somewhere behind simplification, before the compilation takes place, there is a full blown source file. It includes the platform specific initialization and contains the calls to setup() and loop(). When I say full blown source file I mean something that can be passed to the compiler and will compile given that the dependencies are met.
My questions are:

Is this assumption correct?
If so, can someone share an example on how does the full blown source file look like, and where did you get it from?

https://www.arduino.cc/en/Hacking/BuildProcess

The Arduino core libraries (which are nothing more than a bunch of C/C++ files - there is no such thing as the "Arduino" programming language), are compiled along with your source code. These files include all of the initialisation routines and function definitions for things like digitalWrite and so forth.
There is a main.cpp file that gets compiled which is pretty much nothing more than:
#include "Arduino.h"

int main(void) {
    //Initialise timers and things (internal)
    init();
    //Your initialisation stuff (setup)
    setup();
    //Loop forever
    for (;;) {
        //Calling your loop function
        loop();
    }
}

In terms of what your .ino file becomes, it is basically just copied to a temporary build directory and renamed to .cpp. There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.
This process is actually why if you use your own header file which has some typedef in it which you then use in a function call, the code will break because the declarations get added above the #include statements meaning the custom type is used before it is defined.
If you go to the preferences you can tell it to enable verbosity during compilation. This will actually show you exactly what is being compiled. It will also give you the path to the temporary build directory in which you will find the .cpp file with the same name as your .ino file.

There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.  So the .ino file acts somewhat of a library. Makes sense. Will try to get to the main.cpp and expand your answer with the example after which I'll accept it.

Seems a little redundant to use "adruino" language, which then becomes C anyway.

@Serg despite what their website says, and the grand arguments about it, there is no such thing as the "Arduino" programming language, all it is is C++ with a little bit of badly conceived pre-processing.

@TomCarpenter I know, and that's exactly my point - why go to trouble of reinventing the wheel, when they could have just let people work in C/C++ directly ?

C++ (the actual language/compiler that is used) is a multiple-compilation-unit language. There is no single source file, but rather a bundle of compiled source files, that are linked together to create the executable (or downloadable image).
In you case the user sketch provides the setup() and loop() functions, which are called from another source file, which is provided by the Arduino IDE.


text:
Problems with serial communication from Arduino to Bluetooth HC-05
I just purchased some HC-05 Bluetooth devices and I have followed the directions to put the devices in AT command mode by holding EN HIGH when the HC-05 powers up.  When I do this the HC-05 goes into the "slow blink" to indicate it is in command mode.  However, when I send it "AT" I get odd characters in the response.
Note that when I type "AT" I get exactly 4 characters back.  They are just not the "OK" characters I expect.  I also verified that the Arduino IDE serial console is sending both NL and CR characters.
BTW, here is the Mel Patrick HC-05 authored setup program I am running:
https://raw.githubusercontent.com/dmccreary/coderdojo-robots/master/src/bluetooth-remote/hc-05-setup/hc-05-setup.ino

It has been suggested that the data from the HC-05 is only going up to 3.3v and that might be the cause of the problem, since the Arduino is looking for a 0-5 volt signal.
I also note that when I remove the TDX line from the HC-05 that no responses come back.  So I suspect that it is getting the "AT" fine through the RTX from the Arduino to the HC-05.  It is just some problem in the return data format.
Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?
I am also using an Arduino Nano if that makes any difference.
Thanks - Dan

How is it wired? Are you using hardware of software serial? Do you have it set at the right baud rate?

I have wired the RTX and TDX connections correctly and I have set the correct baud rates.  I have another one with similar connections working fine now, but I still don't understand why this device is failing.
I have three theories.  1) The defaults were set wrong in this device and got changed back on reset, 2) or the voltages levels were not working.or 3) I have a bad wire...

Here is the current dialog:
HC-05 BlueTooth Programmer

AT test           a. Set Device Name (a,name)
Version           b. Set Role (b,0)
Address           c. Set Password (c,1234)
Name              d. Set UART (d,Baud,Stop,Parity)
Role              m. Display this menu
UART
State
Password
Device Reset

Blue is what I typed:
1
OK
2
OK
+VERSION:2.0-20100601
3
OK
+ADDR:98d3:31:fb1d15
4
OK
+NAME:t
5
OK
+ROLE:0
6
OK
+UART:38400,0,0
7
OK
+STATE:INITIALIZED
8
OK
+PSWD:1234
OK
a,DAN_ROBOT_1
OK
4
+NAME:DAN_ROBOT_1
OK

are setting the serial monitor to 38400 baud? it s the default speed of AT mode

Strange char in serial monitor cames in 90% of the case from a difference in speed between the Arduino and the Serial Monitor.
In order to have a correct display Arduino (so Serial.begin), Serial Monitor and the HC have to use the same speed. I think as other replied, default speed is 38400.
But, TAKE CARE: as soon as yo change the speed (eg if you change it to 9600), you have to change it on the Arduino and Serial Monitor.

If you use software serial for Bluetooth, you need to set the baud rate and the default baud rate of HC-05 is 38400.
You can change this baud to the desired with AT command.

This is a comment, not an answer.  May I suggest that you flesh out this answer to show exactly how to do these things?

Set Baud rate to 38400 in serial monitor.
If you have Arduino UNO with removable Atmega328p - then remove the chip and connect TX of HC05 to TX of Arduino and RX to RX.
Most of the HC05 works perfectly with 5V system (I have one here hooked up to 5V and RX,TX connected directly ( without level shifter) but it's not recommended.

Try setting your baud at 38400. Connect Tx->Tx & Rx->Rx when configuring your module. Tx->Rx & Rx->Tx during execution.

Why do you need to swap the connections over?

I think WaldoK is confused by the fact that, if you connect something on TX/RX on the Arduino, you can't upload the sketch. So maybe he thinks he has to swap the connections when in fact he just need to disconnect while uploading.

Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?

Yes there are level shifting circuits you can use, resistor dividers and all that stuff, but you will be better off using a proper level shifting circuit, something like this:
Level Shifter
I believe there is something to do with the speed of switching between high and low and getting crisp rise and falls of the signal.

If you are indeed receiving something after the AT command, that means you have the baudrate wrong. Change it from the serial monitor to 38400 or something else.

My experience with these units...

BAUD rate varies so try them all.
Some expect chars in caps and some don't care
Some expect a question mark after the command and some don't e.g AT?
Some require CR and some don't.
Some only stay in AT mode for a second on boot and thus I found I had to set it up in steps, e.g write program to set PIN, then another to set NAME and so on..

Reason for this is that many clones do not have full software and commands installed.