Math with analog input values coming out wrong Im getting stuck in a while loop because Im having trouble running a calculation on some sensor values. When I read my four sensors values and compare the ratio of the first two to the second two, I keep getting 0.00, no matter what the values are. Here's my code:

while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
    if (backleft + backright > frontleft + frontright) {
      myStepper2.step(10);
    }
    if (backleft + backright < frontleft + frontright) {
      myStepper2.step(-10);
    }
    int backleft = analogRead(A0);
    int backright = analogRead(A1);
    int frontleft = analogRead(A2);
    int frontright = analogRead(A3);

    Serial.print("Backleft Reading: ");
    Serial.println(backleft);
    Serial.print("\n");
    Serial.print("BackRight Reading: ");
    Serial.println(backright);
    Serial.print("\n");
    Serial.print("Frontleft Reading: ");
    Serial.println(frontleft);
    Serial.print("\n");
    Serial.print("Frontright Reading: ");
    Serial.println(frontright);
    Serial.print("\n");
    float ratio = (frontleft + frontright) / (backleft + backright);
    float math = (5 + 6) / (4 + 5);
    Serial.print("Math: ");
    Serial.println(math);
    Serial.print("Ratio: ");
    Serial.println(ratio);
    Serial.print("\n");
    delay(500);

  }

Im getting values for my sensors (backleft, backright, frontleft, frontright), but 'ratio' always comes out 0.00. Because of that, Im getting trapped in the loop I believe. What's going on here?

Also, just to check, I added 'math' float as that quick calculation, but I'm getting a value of 1.00 in Serial Monitor. Why? It should be 1.222.

Read this: Integer arithmetic and overflow.

float math = (5 + 6) / (4 + 5);
Serial.print("Math: ");
Serial.println(math);

The compiler is treating your expression (the RH side of the "=" sign) as integers. Thus it is working out:

11 / 9 = 1

Then you assign that 1 to a float. Too late to make it a float! It is already truncated.

Try:

float math = float (5 + 6) / float (4 + 5);
Serial.print("Math: ");
Serial.println(math, 4);  // 4 decimal places

You get:

Math: 1.2222

This also looks wrong:

while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
    if (backleft + backright > frontleft + frontright) {
      myStepper2.step(10);
    }
    if (backleft + backright < frontleft + frontright) {
      myStepper2.step(-10);
    }
    int backleft = analogRead(A0);
    int backright = analogRead(A1);
    int frontleft = analogRead(A2);
    int frontright = analogRead(A3);

How many backleft variables do you have? The one in the while instruction will not be the one you are doing the analogRead on. It doesn't "forward read" variables. I bet you have a different frontleft / backleft etc. set of variables declared earlier. These will not be updated inside the loop.

(To make them get updated drop the word int from inside the loop).


Two Arduinos Send data via Analog Pin? What I want to do is allow Arduino A to send some constant value to Arduino B.

I sense something inherently wrong with my approach, but I cant figure out what it is.

So in the diagram below you will see Arduino A setting its Analog Pin 0 as OUTPUT and write a value 2 every 500ms. On Arduino B we have Analog Pin 0 set as INPUT to receive and print data to Serial. The GND pins of both Arduinos are also connected.

When this setup is executed, Arduino B is constantly receiving data in the form of a 3 digit number starting with 3XX. I am starting to believe this is voltage value?

What is inherently wrong with this idea?

This answer provides both Arduino specific knowledge and general electrical knowledge - both are necessary for a good solution (unfortunately).

Summary

To carry out Arduino analog to analog transfer:

Use analogWrite(pin, value) on a valid digital pin (see below)
Use analogRead(pin) on a valid analog input pin.
Connect a series resistor between the two pins - say 10k.
Place a capacitor from the analog input to ground, say 100 nF to 10 uF.

The R & C act as a low pass filter to convert the PWM to DC.
Details below.

Arduino analog pins are ONLY for analog input, not for analog output.
So trying to do analog out on an analog pin dooms your attempt to failure.

Arduino analogWrite(pin, value) only works on DIGITAL pins and then only on the subset of digital pins that have PWM capability. This is typically digital pins 3 5 6 9 10 11.

"analogWrite(pin, value)  produces as others have said - a PWM signal - rail to rail square waves with mark space ratio that varies so the mean DC value changes. For a 5V system  =
V_DC_mean ~~= value/256 x 5V.
Where 'value' comes from analogWrite(pin, value)

To convert the PWM to good-enough DC a low pass filter with a cutoff somewhat below the PWM frame rate is needed. AFAIK Arduino PWM frame rate is about 800 Hz -  so components are usually higher than that. A simple RC filter where R x C is usefully more than about 0.001S will start to work . Larger RC is smoother but with secondary effects. Using a 10 uF ceramic cap and a 10k resistor is probably OK. 10 uF x 10k = 0.1S. 1uF and 1k = 0.001 s = marginal. An electrolytic cap can be used but leakage current may slightly affect accuracy. So -

From somewhere in Arduino land (unknown) I copied the material below.
This is NOT in the basic reference, but should be.

Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.


Memory leakage caused by String Concatenation In this link, section "Memory, memory, memory" it's been told that doing many String concatenations in sequence, e.g.: using operator+() multiple times, will cause memory fragmentation, which may lead to the fact that total heap not being totally used.

An alternative I'm suggesting is using strcat() with char buffers and not using Strings at all, and then convert from resultant char buffer to String if a String is needed at the end?
Would that be an escape from fragmentation of the heap?

Clarification: I will specify the upper bound of the char buffer beforehand, as if I know the maximum needed/to-be-used size.

If you size the buffer to be able to hold your final string, then yes, that method will avoid the fragmentation caused by the String concatenation function.

Note that String holds the string as a C-style char array internally; it is the concatenation procedure which dynamically allocates and deallocates memory, causing the fragmentation.


Multiple libraries were found for "WiFiClient.h" using nodemcu I am trying to send HTTP requests from nodemcu so I started by uploading the esp8266 library but when I run the following code

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

void setup() {

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

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

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

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

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

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

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

   http.end();  //Close connection

 }else{

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

 }

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

}

i got this error

Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Build options changed, rebuilding all
In file included from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecure.h:41:0,

                 from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiServerSecure.h:20,

                 from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/ESP8266WiFi.h:41,

                 from C:\Users\ELA_HIDRI\Desktop\PFE_ING\nodemcu\nodemcu.ino:2:

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:38:5: error: 'BearSSL::WiFiClientSecure::~WiFiClientSecure()' marked override, but does not override

     ~WiFiClientSecure() override;

     ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:41:9: error: 'int BearSSL::WiFiClientSecure::connect(const String&, uint16_t)' marked override, but does not override

     int connect(const String& host, uint16_t port) override;

         ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:46:12: error: 'size_t BearSSL::WiFiClientSecure::write_P(const char*, size_t)' marked override, but does not override

     size_t write_P(PGM_P buf, size_t size) override;

            ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:58:12: error: 'size_t BearSSL::WiFiClientSecure::peekBytes(uint8_t*, size_t)' marked override, but does not override

     size_t peekBytes(uint8_t *buffer, size_t length) override;

            ^

Multiple libraries were found for "WiFiClient.h"
 Used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\libraries\WiFi
 Not used: C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi
exit status 1
Error compiling for board Generic ESP8266 Module.

so what is this error why i am getting it
Edit
i switched to an other version of arduino ide 1.6.5 the error is gone but it looks like it is not connection i got

Simply Switch

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

to

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


How do I attach 4 input pots to arduino? I am making an arduino game and the requirement is that my arduino reads 4 analog values from the pots. I dont know whether I should use an external battery supply or the 5V from the duino' itself. I dont want my ICs to get fried or nothing happening at all.

It doesn't really matter as long as the the voltage across your pots doesn't exceed the ARef or IORef voltage, which is usually equal to Vcc (3.3V or 5V) for the Arduino boards. It's best to use the 5V from your board. The ADC inputs are relatively high impedance so very little current flows through. Don't use very large value pots or you might not get the correct values from your analog inputs.


Print uint8_t in arduino I'm learning esp8266 using arduino IDE. I'm still a beginner in development board programming. What I've been trying to do is use a crypto library. I am trying out AES in arduino and I chose that library because it seemed complete, and was one of the only library that used ECB. My problem is whilst calling the encrypt function, I get confused with the output.

This is what I've done so far.

#include <Crypto.h>
#include <AES.h>
#include <string.h>

AESSmall128 aes128;

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

  uint8_t key = (uint8_t)1234567654321234;

    aes128.setKey(&key, 16);

    uint8_t output = 0;

    Serial.println("before");
    Serial.print(output);

      uint8_t input = (uint8_t)9164567654321234;

    aes128.encryptBlock(&output, &input);
    Serial.println("after");
    Serial.print(output);

}

void loop()
{
}

When I print output it returns 252. What is 252? Why only 252? It seems really short looking at it. Why doesn't it output strings?

uint8_t is an Unsigned 8-bit Integer, and so the range of values it can represent are 0 to 255.

When you typecast your long/large values to uint8_t, you basically only show the least-significant 8-bits.

However, the decryptBlock() and encryptBlock() functions expect an array of bytes, not a single byte.

The library you link to notes, right in the linked position, that the output and input parameters must be at least blockSize() bytes in length. Referencing blockSize(), it notes that this function always returns 16. So you need to pass an array of uint8_ts of at least 16 length.

When you define your variables for the key, plaintext, and ciphertext, you need to not define then as a single byte type, but as an array of bytes:

uint8_t[16] key =    {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4};  // This is not a good key, btw
uint8_t[16] output = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
uint8_t[16] input =  {9,1,6,4,5,6,7,6,5,4,3,2,1,2,3,4};

(When passing an array, you don't need to dereference the variable, so call aes128.setKey(key, 16);, etc. Omit the &)

Each of the 16 bytes can have a value in the range 0 to 255. They do not have to be limited to single-digit numbers; I just copied/translated what you wrote to demonstrate the example. You could set your key in this way:

uint8_t[16] key =    {66,127,164,72,68,158,148,255,23,36,226,192,198,248,251,221};

You can also refer to bytes with a 2-digit hexadecimal representation:

uint8_t[16] key =    {0xa6,0x09,0x81,0xc5,0xb8,0xf6,0x9a,0x33,0x75,0x24,0xff,0x79,0xd3,0x48,0x4f,0x1d);

UPDATE to address strings

A C-style string is a sequence of bytes, with type char to indicate ASCII data, though any byte-wide type could work in theory. The sequence of bytes ends with a value of 0 (i.e., 0x00, not the ASCII character '0'), so you must remember that the termination byte takes up a byte of memory.

To initialize your key with a string:

const unsigned char[17] key = "helloareyouarehi"; // 16 characters, and 1 byte termination means 17 total bytes reserved in memory.

I have not investigated how the crypto library you are using handles C-style strings, so let's assume it does not acknowledge them at all, and we will have to null-terminate our strings ourselves.

char[17] output = {0}; // Initialized to all zeros
char[17] input = "iwanttoencryptme";

aes128.encryptBlock(output, input);
output[16] = 0x00; // Just to be safe, put the null terminator in the last slot.

Serial.print(output);

If the encryptBlock() function only changes 16 bytes in the output array, then the 17th (zero) could remain from the initialization, but not knowing whether the function preserves strings, it is better to be safe than sorry.


Send a file from PC to Arduino using HC-06 module I want to send a file from my Laptop using its own Bluetooth transmitter to Arduino. Arduino has HC-06 module as receiver.Arduino has SD Card fore store the file.
I was able to send bytes using Python application.
How to send a file using a Python application to Arduino?

Open the file in rb mode in your Python code.
Since the Arduino SoftSerial RX buffer is 64 bytes in size, sending 60 bytes per packet to the Arduino is okay. You basically call out = file.read(60) in python to read 60 bytes from the file and then write these bytes to the Arduino with ser.write(out). You can have the python program wait for acknowledgement from the Arduino, perhaps indicating how many bytes it actually received (after a given timeout period) or what byte was last received. This is just very minor error detection.
The Arduino saves the 60-byte packet to an array and writes everything at once to a file on the SD card, that you've already opened.
After receiving acknowledgement from the Arduino, the Python program reads the next 60 bytes and forwards to the Arduino like before. Continue till the file is exhausted. You could send some sort of signature byte to inform the Arduino that no more bytes are coming and to close the file. Alternatively, a timeout period can be used.

Note: It'll be more efficient if you wrote to the SD card in chunks, where the chunk size is a factor of the card's sector size. 64 bytes is the highest you can do with the default RX buffer size, but thats living dangerously as you risk buffer overflow if anything goes bump.
This can be avoided though, by reading bytes from the RX buffer and into your own array, as soon as they arrive.

Chunks of 32 bytes is safer but it will naturally take longer to send the whole file. Test and judge for yourself.


How to emulate an RFID tag with the RC522 Is it possible to emulate an RFID tag with the RC522? (Spec sheet: nxp MFRC522.pdf)
I want the RC522 to act like a NTAG213 nxp.com/documents/data_sheet/NTAG213_215_216.pdf and to be read/write by other readers/writers.
Are there libraries for that purpose?

No. Looking at the datasheet, card emulation is not a feature provided by the RC522.

Another popular chip, the PN532, does seem to indicate support for that feature, however, looking at the most popular library for this chip from Adafruit, it does not implement this feature. Another library from Seeed, does seem to implement it, but it looks rather limited as to which cards can be emulated, and the library itself hasn't been updated in a while.


Potentiometer on motor for position control I am using a wiper motor as a rotor. I am trying to get it to at least point in different azimuths (compass azimuths eg. 180 degrees) In order to do this, I am thinking about attaching a potentiometer on the axle inside the motor housing to see where the motor is pointing.

So lets say the pot gives me a range of 0-1023. If I divide 1023 by 360 i get 2.84. So lets say the pot gives the Arduino a 1, I can relate that to 2.84 degrees?

Also, what if the motor is pointing at 350 degrees, and I want it to point at 2 degrees. Instead of it turning around 348 degrees, it just cross pass 360 and go to 2 degrees.  How would a pot handle going over a single step? If the motor passed a single step would it consistently give me a 1023 reading?

I am trying to get a wiper motor to have a known position 360 degrees around.

I am trying to get a wiper motor to have a known position 360 degrees around.

There might be a few possibilities.

First there are continuous rotation potentiometers on the market. They seem expensive though and I can't comment on how accurate they are.

Second, if your device is only ever going to turn through say ten revolutions then go back, you could just get a multiturn pot that will handle that range of turns. (Depends what you're building of course - for example I've heard of servo winches for model sailboats that use this method.)

Thirdly, and I accept this may not be a good answer to your question, but have you thought about using incremental encoders instead? In theory they could be more accurate too. The hardware is quite easy but a bit more programming is required to make these work...


What does a higher clock signal frequency actually mean for my AHRS? I've got an Arduino with an ATmega328 processor. It can be operated at 3.3V which nets a clock signal frequency of about 12 MHz respectively 16 Mhz at 5V.

I've got an IMU connected to the Arduino and a AHRS algorithm turning accelerometer, gyroscope and magnetometer data into orientation data.

What does the higher frequency of 16 MHz actually mean in this context?

Will the AHRS be calculated faster so I get a lower latency? Can I poll the sensors more often? I want a deeper understanding of what I'm doing here.

What does the higher frequency of 16 MHz actually mean in this context?

The Arduino will run a bit faster (33% faster). Therefore it could calculate things faster. Whether you can poll the sensors more often might depend on the sensor. Limiting factors could be how fast you can communicate with the sensor, how often the sensor takes readings, what you are going to do with the readings, and whether it matters if calculations are a bit slower.

For a better response I suggest you post a link to the particular sensor, the AHRS algorithm you are using, and describe the application you are using it for.


Servomotor and music shield I’m trying to make an art sculpture, with an Arduino-uno, a servomotor and a seeduino musicshield v2.0.
I’m making the servo motor moving a stick with the attached fans of the servo, and I want to  synchronize the servo motor with the music shield  and when the motor is stopped(about one minute), the music(about one minute of music) will play and when de motor is moving the music will be stopped.

I'm super noobie with the code. I tried something like this
but, is not moving at all, neither my servo or my musicshield  when I write this:

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

#include <Servo.h>
Servo myservo;

int val;//for the servo

void setup() {
  //setup for the music shield
  Serial.begin(9600);
  player.begin();  //will initialize the hardware and set default mode to be normal.
  player.addToPlaylist("a.mp3");
  //setup for the servo
   myservo.attach( 9 );
}
void loop() {
  mover();
  if ( val == 90) {
    music();
  }
}

void mover () {
  val = 0;// start point
  myservo.write(val);
  delay(800);

  val = 90;
  myservo.write(val);
  delay(60000);//wait for 1 min
}

void music () {

  player.play();
}

when I write this my servo moves, but obviously my music wouldn't play

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

#include <Servo.h>
Servo myservo;

int val;//for the servo

void setup() {
  //setup for the music shield
 Serial.begin(9600);
  player.begin();  //will initialize the hardware and set default mode to be normal.
  player.addToPlaylist("a.mp3");
  //setup for the servo
   myservo.attach( 9 );
 }

void loop() {
mover();

 }

 void mover () {
val = 0;// start point
myservo.write(val);
delay(800);

val = 90;//
myservo.write(val);
delay(60000);//wait for 1 min
}

void music () {

  player.play();  //do some leisurely job
}

And the music will play when I write this, obviously the servomotor don't move, so I'm  think I have a problem mixing my servomotor and the musicshield(seeeduino music shield v2.0, and I want the music start when my servo motor is in this point of val=90 delay(60000)

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

    #include <Servo.h>
    Servo myservo;

    int val;//for the servo

    void setup() {
      //setup for the music shield
     Serial.begin(9600);
      player.begin();  //will initialize the hardware and set default mode to be normal.
      player.addToPlaylist("a.mp3");
      //setup for the servo
       myservo.attach( 9 );
      }

    void loop() {

   player.play();
     }

    void mover () {
    val = 0;// start point
    myservo.write(val);
    delay(800);

    val = 90;//
    myservo.write(val);
    delay(60000);//wait for 1 min
    }

Is this the MusicPlayer.h that you have?  https://github.com/Seeed-Studio/Music_Shield

From the description it says:

  The music player reads data from SD card and then feed into the VS1053 chip via SPI bus. This is done in TIMER1's ISR with a interval of 2ms. This job has a high priority and uses the cpu exclusively. In the spare cpu time, player does some process control, like play/pause.

That's the same timer that Servo.h uses.  So the two libraries are not compatible.  You could try using ServoTimer2 library or rewriting this library to get the 2ms timer with Timer 2.


Arduino wait for change in value I am currently working on a project that involves steering wheels, and I would like a way for Arduino to wait for a change in value. A potentiometer is used and I would like a program to run (say, like lights blinking ) until there is a change in value of the potentiometer ( like an increase in 300).

Thanks in advance.

EDIT
I realized that I did not give enough information about what I want, so here is the actual task I am trying to achieve :

The lights goes on when :

Button is pressed

The lights goes off when :

The button is pressed again

or

Another button is pressed

or

Potentiometer increases or (only one of it) decreases by 300

Plus I didn't mention that the value of the potentiometer will be constantly changing so the old value for the potentiometer should be the one right after the button press.

Soooo sorry for the inconvenience caused. ( I am really bad at programming)

int oldValue;
void setup()
{
    oldValue = analogRead(A1);
}

void loop()
{
    int value = analogRead(A1);
    while( abs(value-oldValue)<300 )
        delay(1);
    oldValue = value;

    // start blinking lights here, as the value has changed by at least 300

}


Arduino messing up as slave over I2C I have an Arduino Mega2560 and a Raspberry Pi hooked up through I2C. The Pi is acting as the master, while the Arduino is the slave. While sending data over I2C, the int message gets messed up and will either send the address or the data. Then I can't even receive any useful data from the Arduino.

So if I turn the receiving function off it sends the data just fine, but when I ask the Pi to start receiving data again it slows down the entire bus and data starts conflicting between the Pi and Arduino. Also it only happens with the Arduino. Every other device works flawlessly.

Here's what my code looks like on the Pi side. I'm using SMBus to send and receive bytes. I didn't bother to put up code for it because I don't have the source code for SMBus. I just trust that they work because my other I2C devices work without a hitch.

while True:
    #if alternating == true then get the imu if not then get the motor speed
    if alternating == True:
        try: #need the try because an error will stop the program completely
            ypr = IMU.getYPR()
            yaw = int(ypr['yaw'] * 180 / math.pi)
            savedYaw = yaw
        except:
            yaw = savedYaw
            #print "exception"
            pass
            #write yaw to arduino
            i2c.writeByte(yaw)
            alternating = False
        else:
            #start reading data from arduino
            #readArduino()
            alternating = True
            pass

Then on the Arduino side these are my onReceive and onRequest functions:

void readPI(int byteC) {
    if(Wire.available()) {
        reference = Wire.read();
    }
    pid1.getReference(reference);
    pid2.getReference(reference);
}

void sendPI() {
    int values[] = {(int)out, (int)outReversed  };
    Wire.write(values[count]);
    count++;
    if(count > 1) {
        count = 0;
    }
}

Is there something about the Arduino that I don't know? Maybe it's a timing issue? Is there a way to set up registers? I can either receive or send, but I can't do both, and Googling the problem only leads to an example of someone sending 1 - 9 over the Pi. I can't find examples of anyone actually doing something complicated with an Arduino and a Rasp Pi over I2C. Any and all help would be amazing!

I find your onRequest function obscure:

void sendPI(){
     int values[] = {(int)out, (int)outReversed  };

     Wire.write(values[count]);
     count++;
     if(count > 1){
     count = 0;

     }
 }

Why only send one byte? I think you have a number of problems:

The size of int on the Arduino Uno is 2 bytes, on a Pi it is 4 bytes. So there is a mismatch there for a start.
Wire.write (written like that) sends one byte, so that is only going to be half of your int. So that is even less.
It isn't obvious what the Pi end is doing, but to make the int sizes match, I would be sending the lot in one hit like this:

void sendPI(){
     long values[] = {(int)out, (int)outReversed  };
     Wire.write((byte *) &values, sizeof values);
 }

Now you just read 8 bytes on the Pi (two ints).


AC ceiling fan speed control using arduino Uno R3 How can I control an AC ceiling fan speed using Arduino Uno R3? I cannot understand the key behind controlling AC voltage using Arduino (though I know how to on/off ac appliances using arduino and relays).

Controlling the speed of an AC motor is not an easy undertaking, and messing around with mains voltages if you're not experienced and know what you're doing can be fatal.

Now that's the disclaimer out of the way, on to your question.

Unlike DC, you cannot use PWM to control the average power of AC.  That is, after all, what PWM does - the on-off ratio creates a percentage of the power - but it can only be done if the incoming power is of a steady state.

For AC there are two ways of reducing the output power - either reduce the voltage, which can be done with resistors (look inside a multi-speed fan and you'll see resistors to change the speed); or chop up the AC waveform, which is a little like PWM but more specialized.

If you only want specific speeds then you could pre-define them using resistors and switch different resistor combinations in and out using relays.  It's crude, but simple, and also probably the safest option for the beginner.

If you want proper variable speed, though, then you're going to have to chop up the waveform.  The theory is quite simple:  Start where the waveform crosses 0V in either direction, with the output on, and turn it off again at some percentage of the way through the cycle.

Like PWM it's the on-off percentage that defines the output power (and thus the speed), but timing is critical - you must start the PWM sequence at 0V and it must last exactly one cycle.

A number of simple circuits work in the opposite way - they remain off until the input waveform reaches a certain point, then switch on, until they reach the zero-crossing point.  While simple, these circuits aren't good.  The reason being that the sudden rise from 0V to the "trigger" voltage when the output becomes live can cause large spikes and noise in the circuit, which can cause lights to blow etc.  It's the same effect as why bulbs most often blow when you turn them on, not when they have been running for a while - it's that very rapid rise from 0V to a high voltage which causes them to be over-stressed and blow.

So any circuit you choose should really be a proper one which turns on at 0V and turns off after a period, not turn on at a voltage and turn off at 0V.


Ethernet Shield - Multiple simultaneous connections cause TCP reset I have a very inconvenient problem with a web server I'm writing for a Arduino Mega 2560 with a W5100 Ethernet Shield (with the "official" Ethernet lib). I wrote the server code and it works like a charm, BUT there is a condition, when the server won't accept all the TCP handshakes and resets the TCP connections:
When I load a big webpage, the browser (Firefox and Chrome too) asks for the .htm first, then collects the links in the file and request them all simultaneously and that's when I got the problem:

The server gets multiple TCP connections but it only accepts the first, then dumps all the others (by TCP reset). After that the client sends them again and the problem starts again: the server accepts the first and drops the others. And so on, for example if the browser needs 3 files, it will take ~9 seconds, because of the retransmission delay. (3 + 6 seconds) Eventually the webpage will load, but a 10 second delay is not acceptable.
Is there any way to cache the requests on the Ethernet Shield or to tell the browser to wait a bit between requests or any other way, to wait a bit for the Arduino to finish the previous request?

Snippet for the server, Wireshark and Chrome network data: https://gist.github.com/anonymous/181f359b70d69e4470931204c4ec175c

Thanks for the help!

G.

I have received a request from the OP to move this to Network Engineering because it got no answers. I'm going to decline this for the moment because I doubt they will be familiar with the Arduino Ethernet shields.

The low-cost shields have a known limit on the number of connections they can handle simultaneously (no doubt limited by available RAM). From the page Arduino Ethernet Shield 2 we learn:

  It supports up to eight simultaneous socket connections.

You don't seem to be getting that, which makes me wonder if it is a code issue. It might help to post your code. If you make code that "blocks" while handling the first connection you may not accept the other ones in a timely way, leading to a reset.

Please post a Minimal, Complete, and Verifiable example.

I did a post about a tiny web server for the Arduino which uses a state machine to handle incoming data without blocking.

You may also be able to help yourself by using the HTTP header that requests that the connection be kept open, eg.

Connection: keep-alive

That might stop the client opening new connections in quick succession.


Read multiple char from USART int i, j;
char data;
int flag=0;

void loop()
{
if(Serial.available() > 0){
    data  = Serial.read();
    flag=0;
  }

  if (data == 'd' && 'b') {
    digitalWrite(cONOF, HIGH);
  } else if (data == 't' && 'w') {
    digitalWrite(cONOF, LOW);
  }

  if (data == 'y' && 'w') {
    digitalWrite(start, HIGH);
    delay(2000);
    digitalWrite(start, LOW);
  }

  if (data == 'e' && 'r' && 'h' && 'i') {
    for (i=0;i<10;i++) {
      digitalWrite(horn, HIGH);
      delay(100);
      digitalWrite(horn, LOW);
      delay(100);
    }
    for (j=0;j<10;j++) {
      digitalWrite(horn, HIGH);
      delay(500);
      digitalWrite(horn, LOW);
      delay(500);
    }
    digitalWrite(horn, LOW);
  }

}

I want to read data from the USART where the messages have more than one character. I tried the code above but it doesn't work well. For example, I want to send the message 'db' to turn the output on, but just sending 'd' also turns it on, how do I fix this?

You need split the reading into two processes - storing the characters and checking if they are the right message.

To store the characters for example:

String message = "";

void loop()
{
while(Serial.available()) {
    char b = Serial.read();

    if (b == '\r') {
        processMessage();
        message = "";
    }
    else {
        message += b;
    }
}
}

The process might look like

void processMessage() {

    if (message == "fb") {
         foo();
    }
    else if (message == "bf") {
         bar();
    }
}

I just use the Messenger library usually. But note you have to change WProgram.h to Arduino.h in Messenger.cpp to get it to work.


The PCM libary won't work on an Arduino Nano I'm using the PCM(http://highlowtech.org/?p=1963) library on the Arduino nano, I'm plugging the speaker(https://www.amazon.com/gp/product/B07WZP4QFK/ref=ox_sc_act_title_3?smid=A2O4FZXIRZDLHA&psc=1) into pin 11 and ground, but the example file won't work.

I guess the Nano had a sketch which was setting pin 11 HIGH (using SPI?) as you turned it on with a 4 Ohm speaker attached without any other resistance. It created a short circuit and damaged the pin's circuit.
Using tone() or the PCM library with a speaker connected without additional resistor doesn't damage the pin immediately because it is then HIGH only for very short moments, but it stresses the pin circuit too.
The linked page recommends to use direct speaker connection because it is much louder then with a resistor in series, but this is a wrong advice. It should recommend an amplifier module for example with LM386 IC.
A piezo speaker has higher resistance so it can be connected directly to Arduino pin, but a piezo sounds loud only in high frequencies so with the PCM library the sound is like whispering.


Digital to Analog converter with DAC5311, Any suggestion? I made my DAC code with DAC5311 and Arduino Uno.
I think it has no problem, but it doesn't work well. Just print 0.(I use an oscilloscope.)
I don't know where has the problem. Please give me any suggestion.

#include <SPI.h>
#include <math.h>
#define pin_CS 10
#define pin_MOSI 11
#define pin_SCLK 13
#define max_VOLT 5

void setVoltage(float voltage){
  if (voltage < 0) voltage = 0;
  if (voltage > max_VOLT) voltage = max_VOLT;
  uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
  temp = temp << 6;
  uint8_t upper = temp >> 8;
  uint8_t lower = (temp & 0xff);
  digitalWrite(pin_CS, LOW);
  SPI.transfer(upper);
  SPI.transfer(lower);
  digitalWrite(pin_CS, HIGH);
}

void setup() {
  Serial.begin(9600);
  pinMode(pin_CS, OUTPUT);
  pinMode(pin_MOSI, OUTPUT);
  pinMode(pin_SCLK, OUTPUT);
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  digitalWrite(pin_CS, HIGH);
}

void loop() {
  setVoltage(5);
  delay(10);
}

Classical +/- 1 problem

If you do this calculation by hand uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
you will get temp=256 and this is a value you can not convert with a 8 bit DAC.

Try uint16_t temp = int(voltage * (pow(2, 8)-1) / max_VOLT); instead.

(or event better for a µC uint16_t temp = (uint16_t) (voltage * (255 / max_VOLT));)


How to access variables by variable? (I.e. variable variables?) Can Arduino handle variable variables?

function getLetterCode(char input) {
    int letter_a = 17;
    int letter_b = 42;
    int letter_c = 50;
    return letter_$$input$$; //pseudocode
}

This is just a stripped down code to demonstrate my question. I am aware of arrays, the switch structure and other workarounds, but for my specific need variable variables would save tons of typing.

No, you can't do that sort of thing. That sort of thing is only possible on interpreted languages where the name of the variables is seen at runtime.  In compiled languages you can't see the variable names (they no longer exist) so you can't access them by name like that.

Instead you need to either store your variables in a simple array and access them by index, or create an array of "key/value" pairs (simplest to use an array of a struct) and iterate it looking for the right key to match with your input.  Or, if there aren't too many inputs, simply use a switch to select different values:

int getval(char input) {
    switch (input) {
        case 'a': return 17;
        case 'b': return 42;
        case 'c': return 50;
        default: return 0;
    }
}


How to approach an complex Arduino Uno project (Serial, SPI, Ethernet) in pure C, without libraries? I have a college assignment where I need to get serial output, the Ethernet shield and SPI communication with other boards to work. We are not allowed to use any existing libraries, though we can use them as strong inspiration, as long as we are able to explain every line we have in our final code.

Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries but I am hopelessly overwhelmed by anything beyond getting a pure C blinky to run.

Do you have any idea how I should approach this? Are there C resources about the Ethernet shield and Arduino SPI?

As Hans Neve wrote, you should really refer to the docs.

This is how it works in real life, when you want to write a driver for a new piece of HW.

You have to at least understand the block diagram, programming models and register sets of the device you want to control.

Then read whatever existing code you might find. In the practical case you have the driver for the version N-1 of the HW. Or maybe for something close enough.

As generic programming advice goes:

avoid any dynamic memory allocation, you will thank yourself later on, when you do not have to debug unexplained memory issues
if you want to write a driver, consider making it reentrant, should the same code be shared across multiple IP blocks
if you want to use OOP, avoid anything that requires runtime lookup. The compiler should have enough information to resolve everything statically.

WRT debugging: both device drivers might suffer from interference if you try to use the serial port. Consider using some ICD tools, like the AVR Dragon. Alternatively, you might find that debugging over I2C is less penalizing. But you have to define your debugging messages.


How to wire an LMD18200 and an arduino? Ive been working with a motor project for a while and i bought this H-bridge(LMD18200). I dont understand how im supposed to connect it to the arduino.

Here is the datasheet for the lmd18200:

Most basic way would be to use only DIR, PWM and Break.

Use Break as enable (put high at begining of the program, put low when you want to start rotation).

Use Dir to change rotation of the motor (usually high is CV, low is CCV, but you need to check the datasheet)

And hook up PWM to PWM pin on arduino. This will control the speed.


Control multiple WS2812B strips with different leds count First of all, my English is not that good so sorry if I made any mistake.

I'm using the WS2812FX, an awesome WS2812 effect library base on Adafruit NeoPixel library to make a small controller for the lightning in my bedroom.

The question here is how do I use this library to control multiple WS2812b led strip with different leds count, like one strip with 30 leds the other with 55 leds but the effect will just cycle through each individual led of each strip.IF somehow I can add one more output pin to this.

Example : There is an effect call "Larson Scanner" will light up one led then it run from the first led to the last led and go back, I want it to do the same on both strips, on the 30 leds strip it goes from first led to 30th led then go back & on the 55 leds strips it goes from first led to the 55th led at the same time.

Hope you guys understand what I'm asking :(

Link to the library : https://github.com/kitesurfer1404/WS2812FX

The WS2812 chip requires highly timing dependent pulses to work, as I describe on my page about Neopixels. We are talking about pulse widths of 350 ns.

I suggest it would be impossible to add another strip "if I can add one more output pin to this". It's not a question of adding pins, it's being able to output pulses that fast. You can't do it, at least not on the AVR Arduinos, and I doubt that the ones with faster chips would do it either.

What you could do is connect the various strips together so it is really one long strip (assuming they aren't too far away from each other). The different strips could usefully have their own power supplies, but the data and ground would need to go from the Arduino into the first strip, then out to the second one, and so on.

Something like this:

As for synchronizing the strips, well that is just programming. If you want the first LED on the 30-LED strip to light at the same time as the first LED on the 55-LED strips, then you actually would need to light LED #1 and LED #31 at the same time.

Possible alternative

Actually what might work would be to send to strip #1 first, and then strip #2 after changing pins. That means you would have to interleave the sends. For example to make a pixel seem to run backwards and forward on two strips you make it move one pixel on the first strip, then one pixel on the second strip, and so on.

I'm not sure if the library you mentioned supports that, since the LED count is in the constructor. It looks like it might, as you can change the number of LEDs and the pin number.

You might be able to make two instances of the library object (with different names), initialize them both, and then interleave the sends between them.


Passing variables for a PID in an interrupt I'm needing to pass variables from my timerIsr() function to my loop() function. I have little experience with the Arduino language, I'm mostly familiar with Python so this has been quite difficult for me.

Essentially I'm creating a PID controller to maintain RPM of a fan motor if friction is applied to it. I'm implementing the PID control in the loop() function but I need the rotation variable information from my timerIsr() function. I've tried to return the variable info but it doesn't match up to the actual fan speed. I think it has something to do with difference delay/timer times operating at different instances but I'm unsure.

Here's what I have so far

#include "TimerOne.h"
#include <PID_v1.h>

int counter=0;

const int IN1 = 11;
const int IN2 = 10;
volatile float pot=0;
const int POT = 0;
const int ENA = 6;

double Setpoint, Input, Output;
double Kp=2, Ki=5, Kd=1;

PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void docount()  // counts from the speed sensor
{
  counter++;  // increase +1 the counter value
}

void timerIsr()
{
  Timer1.detachInterrupt();  //stop the timer
  Serial.print("Motor Speed: ");
  int rotation = (counter / 30);  // divide by number of holes in Disc
  Serial.print(rotation,DEC);
  Serial.println(" Rotation per second");
  counter=0;  //  reset counter to zero
  Timer1.attachInterrupt( timerIsr );  //enable the timer
  Serial.print("pot = ");
  Serial.print(pot);
  Serial.print("\n");

  //return rotation;
}

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

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);

  Timer1.initialize(1000000); // set timer for 1sec
  attachInterrupt(0, docount, FALLING);  // increase counter when speed sensor pin goes High
  Timer1.attachInterrupt( timerIsr ); // enable the timer

  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  //Input = timerIsr();
  pot=analogRead(POT)/4.01569;
  //Setpoint = sp;

  //Serial.print(Input);

  analogWrite(ENA, pot);
  digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
  digitalWrite(11, LOW);

  delay (250);
}

As you can see I've commented some stuff out that's related to the PID library. Right now I'm just trying to pass the rotation variable to the loop() function.

Is it possible to update global variables at different times so any function can access them?

Short answer: Yes, it is possible to update global variables from interrupt routines, but it comes also with problems.

Long answer:

First you have to understand, how interrupts work. You are using a timer interrupt and an external (pin) interrupt. The compiled program lies in the flash of the chip. At the start there are some special addresses for the different interrupts. If the hardware then registers a condition for an interrupt, it will stop the execution of the main code (the code, that was executed, when the interrupt condition occured), saving the current state and jumping to the corresponding address, where it get's send to the ISR (interrupt service routine), that you defined (in your case the function docount()). After the execution of this program the microcontroller will return to the execution of the main code (by restoring the previously saved state and jumping there). An ISR can only have a return type of void (no return value), because when it returns, there is no special code to receive and use this value. The interrupt may occur at different times every time.

Instead it is common to write global variables in the ISR. For this you have to consider some points:

Global variables, that may be changed during an ISR, has to be declared (additionally to the type) as volatile. This means, that the compiler cannot optimize this variable (for example to a local variable) and has to consider, that it may change anytime, so that he cannot use a cached value.
The usage of the variable in the main code has to be atomic or secured against changing of the variable. If you use a variable in a calculation, it may take many cycles for it (especially if you have a big datatype or some expensive calculations as with float). If the interrupt occures in this time, the value might be changed in the middle of calculation, making the result a bunch of garbage. If the calculation only takes 1 statement cycle, is cannot be interrupted and is called atomic. Since this is rarely possible, you can enclose the corresponding code into securing code. For the Arduino platform, you can use the noInterrupts() and interrupts() functions, to turn off all interrupts, do the calculation and turning the interrupts on again. Be sure do turn the interrupts off only for a short time, so that you don't miss interrupts. Often this is only used to copy the variables value into a local variable (local working copy), which then can safely used for calculations, while the global variable may still change.

Besides that, you also have to think about, what code you write into an ISR. An ISR cannot be interrupted by another interrupt. So functions, that depend on interrupts to work, will not behave like intended. The delay() function for example will simply block all code execution, since the return of the millis() function will not change (it depends on the timer0 interrupt). In your Timer1 ISR, you use Serial.print(). This function can be used, but only until the Serial libraries buffer is filled. The actual communication will take place, after the ISR returns, because it also depends on interrupts. When you try to send more, than fits in the buffer (64 bytes), you will loose data. Currently you should be below that, but you should have this in mind, when coding.

I don't think, that you really need a timer interrupt for calculating and outputting the data every second. Here I would use a non-blocking coding style in the loop() function, like you can see in the BlinkWithoutDelay example, that comes with the Arduino IDE. This is better than using delay(), which is just busy waiting. You save a timestamp with the millis() function and check the time difference. That saves Timer1 for other purposes and also refactors your main code for being extendable and non-blocking, if you want to add more functions.

As I read from this example from the PID library, you need to call myPID.Compute() once in a while to do the PID calculations with the new values. Since these only change every second, you should call this function directly after the calculation of Input.

All in all you need something like this (I didn't include all the code, just the important part, so that you should be able to understand the principle):

unsigned long timestamp;
#define INTERVAL 1000

void loop(){
    if(millis() - timestamp >= INTERVAL){
        timestamp += INTERVAL;
        noInterrupts();
        int counter_copy = counter;
        interrupts();
        // Do the calculations with counter_copy and same the result to `Input`
        // You can put the code from your timerisr here (without the Timer1 code)
        myPID.Compute();
    }
}

Your pot code then should also be enclosed in such an if statement, to prevent, that the PWM get's restarted again and again very fast. If a reaction time of 1s is ok for you, you can put this code in the if statement above. If you want faster reaction times, you can add a second if statement like this to the loop() function (including it's own global timestamp variable and interval value).

The digitalWrite() calls for the direction can be put into the setup, since they don't ever change in your code.


How do you connect parts once all GPIO ports are used? I have a rather ambitious project in mind. Lots of buttons, sensors, feedback.

If I run out of GPIO ports to attach stuff to my Arduino, what's next? Do you have to buy a separate Arduino to run the extra parts, and then link the two arduinos somehow?

Thanks for any direction you can give.

Yes, it is one possible way, another are using some kind of multiplexing as input shift registers, Charlieplexing http://www.instructables.com/id/Charlieplexing-7-segment-displays/?ALLSTEPS, button matrix http://pcbheaven.com/wikipages/How_Key_Matrices_Works/ or i2C bus, which can connects up to 127 different i2c devices


How to make an SMS notification to my phone with Arduino Uno? I am planning to make an SMS notification to my phone with Arduino Uno via a push of a button.

I have an Arduino Uno C520A Embedded System. Is it possible to do so with this model ? If yes, which WIFI module should I get ?

I just want to make an API request to the web through the push of a button.

It is possible if your provider has a sms gateway e-mail-address. Just google which it is for your provider (e.g. number@tmomail.net for T-Mobile (US)). And there should be a lot of tutorial about how to send an email with an arduino.

Every wifi-module with arduino support will work if your WiFi is a standart 3.6Ghz. And yes it should work with any arduino compatible microcontroller.


Problems running Arduino project off a 9V battery I have been working on an Arduin Uno Rev2 project for a while now. I have been developing using my MacBook, downloading code through the USB jack running it, monitoring the serial output on my MacBook, etc.

The Arduino is being powered from my MacBook through the USB jack which is also carrying the serial output back to the MacBook.

But now I want to make this project portable. IE: instead of powering it off a wire from my Macbook, I want to power it off a battery. So I followed these instructions #4 and connected up a 9V battery to the VIN pin.

At first it seemed to work. But very soon started noticing great instability. There are many serious problems I need to solve working off this battery:

As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?
I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?
I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.
I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.

As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?

Probably because although the voltage is high enough to cut off the power from the USB port it's not got enough current to run the main MCU properly.

  I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?

Because 9V batteries can't provide enough current.

  I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.

No. The voltage drops rapidly to about 8V then down and down and down until it's below what the regulator can regulate. You can see this curve in any battery datasheet.

  I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.

That's nonsense. The current demands will be whatever the circuit needs at any moment in time. There will be an upper limit to that demand (defined by your circuit and what you are doing at any one time - the peak current draw) and your power source has to be able to provide at least that amount of current.  If you try to draw more current than the battery can handle then the output voltage will drop to a level where it can no longer power the circuit properly. It is at this point you get "brownouts" and the board resets randomly and strange unpredictable things happen.

In short: never use a 9V battery for an Arduino project. It's fine for vert low power operations, which take careful design, but for general use stay away from them. Also the Arduino's built-in regulator is a very inefficient and will waste about 25%-40% of a 9V batteries power before you even begin. Instead you should use a more efficient switching regulator to provide 5V directly to the 5V pin (or USB port) from suitable higher capacity batteries (such as AA cells).

As a comparison here's some typical battery discharge graphs comparing alkeline AA to PP3 (9V). These are both Duracell Ultra.

As you can see the PP3 drops its voltage very rapidly even under a light load. Under a "heavy" load (what would be considered a very light load to an AA) it tumbles away to next to nothing in no time at all.


Burn Bootloader to Chinese Arduino 2560 with AVR ISP programmer I got my hands on one of these ISP programmer for Atmel AVR microcontroller in USB stick design:

Then I selected Progammer > AVR ISP and clicked on Burn Bootloader but it says

stk500_recv(): programmer is not responding.

Has anybody any experience doing this and if so, could they point me in the right direction?

Edit:
I've also added the following to programmers.txt

mySmartUSB.name=mySmartUSB
mySmartUSB.protocol=stk500v2
mySmartUSB.communication=serial
mySmartUSB.program.tool=avrdude
mySmartUSB.program.extra_params=-P{serial.port}

That error is common and usually means you either have the wrong board selected or the wrong port.  Check the tools menu. Be sure you have the port for the programmer and not the port for the board if the board is also connected.


Arduino LCD Brightness I've made this small device that uses a ultrasonic sensor to tell how far away an object is and display it on a 16x2 display.

Here's the code:

#include <LiquidCrystal.h>

int Contrast=100;
 LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int trigPin = 7;
const int echoPin = 8;
// defining variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
  analogWrite(6, Contrast);

  lcd.begin(16, 2);
  lcd.clear();
}
void loop() {

// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration / 29 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
  lcd.setCursor(0, 0);
  lcd.print("Distance: ");

 lcd.setCursor(0, 1);
  lcd.print(distance);
  delay(100);
  lcd.clear();
}

Every thing works fine apart from the fact that the lcd backlight is too dim(barely visible). I tried looking online but is there any way i can get max brightness without a potentiometer? I do have resistors , can i use them somehow?

The back light of the LCD is just an LED connected through a resistors on the A (15) and K (16) pins on the display. The LED doesn't require an external resistor since according to the datasheet there is a build in resistor on the board itself. If you aren't using any external resistors and applying a constant voltage of 5V and the screen is still dim than this means that the led is most likely dead and you would need to replace the back light panel.

If you are talking about the contrasts of the display. Than I would recommend you to hook up the contrast pin to a PWM pin on the Arduino and by using analogWite to tune the display in order to get the desired value of contrast.


How to make arduino show cpu usage with 10 leds? So i want to make arduino show my computer cpu usage with leds, for example if 10% then 1 led will light, if 50% then 5 leds, if 80% then 8 leds...

There's three basic steps you need to cover:

Get the CPU usage of your computer
Communicate that to the Arduino
Have the Arduino respond to the data

We can't really help you with step 1.  That's outside our remit.   You should head over to StackOverflow for that. How you would do it depends on your host OS since each one has its own way of reporting it.

For step 2 you would need to write software for your computer, incorporating what you have learned from step 1.  Once you have the correct data you need to send it over to the Arduino through its serial connection. You'd need to come up with a good way of doing that, but probably just sending the usage percentage as plain ASCII text separated by new-lines is probably simplest.

Step 3 would entail reading in the data you sent in step 2, deciding what the numbers you have got mean, and then turning on the relevant LEDs.

Another option, which might simplify things a little, might be to use something like Firmata, where your PC sends the instructions to turn the LEDs on and off, and the Arduino just becomes a kind of dumb interface that doesn't do much on its own.


Shift register with relay board behaving erratically I have a nodemcu connected to a shift register(https://www.amazon.de/gp/product/B07CHBYR7Z) to control an 8 channel relay board (https://www.amazon.de/Elegoo-Relaismodul-Optokoppler-Arduino-Raspberry/dp/B01M61VVGV). The realy board is connected to various pumps. The setup itself works quite well normally. However after some switching cycles or when I manually bridge the relay to activate a pump the shift register suddenly either doesnt react at all. Switches on everything or is off by one. I read that it might be possible that I have flow back from the relay coil so I added the diode over the gnd and vcc pin of the relay board. However that didnt help either. Can anybody tell me what I am doing wrong? I hope the schematic is legible.

If this is a noise issue, there are a number of mitigating actions to consider.  Also, consider that most if not all noise mitigating approaches are generic and may not apply to all situations.

It is almost always easier to mitigate noise at the source.  Filtering the power & shielding are two approaches.
When laying out digital integrated circuits, it is common to include bypass or decoupling capacitors as near as possible to each integrated circuit.  If unfamiliar with these, these capacitors go across the power pins of the integrated circuit.
If an electrically noisy environment is anticipated, making all communication leads and cables as short as possible prevents the likely hood of unexpected results.
If cables need to be long different communications methods such as balanced line or differential signalling should be considered.
Bring all power grounds to a single point.  This mitigates current loops which can cause unexpected power voltage fluctuations.
Consider the power requirements and generally use a power supply that is rated for double to have a margin of safety.
Avoid running cables containing high power or switched power near or in parallel to cables containing low voltage logic.

For this particular application / design:

Likely the reversed bias diode on the relay power supply lines is not needed.  There appears to be optical isolators on the relay board which should prevent the inductance of the relays from feeding back.
Verify you are creating the correct signal to the 74HC595 chip.  Use the timing diagrams on page 8 of this ti.com 74HC595 specification sheet as a guide.
Consider the gauge of the power cables.  Thinner wires over longer runs will drop the voltage proportional to the current demand.  If all 8 relays are active, the current demand may be as much as an Amp.


how to drive 500W of leds I am currently developing a project that needs 9 led stripes, each led stripe has 5 meters, 300 leds, it consumes 60W per stripe in a total of 540W...

This are the led stripes - 5M 12W/M 24V SMD 2835

This led stripes use a 24V power supply.

The thing is I want to drive them with an arduino and PWM. What would I need to do it. I was looking for something like CAT4101 but I never dealt with so much power before and I would like your advice.

Thanks

The led strips will have their own current limiting / drivers. A couple of quick calculations:

24V at 12W is (I=P/V) 12/24 = 0.5A per meter
5 meters = 0.5*5 = 2.5A

So each strip takes 2.5A. The CAT4101 is a 1A max driver, but since it is a constant current driver it's not suitable for a strip that has its own current control built in.

I suspect each meter consists of 10 chains of 6 LEDs with a current limiting resistor or two. Out of interest, calculations:

6 LEDs at (say) 3V forward voltage would be 18V.
24 - 18 = 6 volts to drop
500mA divided by 10 chains = 50mA
R=V/I = 6 / 0.05 = 120Ω current limiting resistors.
P=I²R = 0.05²×6 = 300mW dissipated from the resistors.

Instead all you need is an N-channel MOSFET as a low-side switch that can operate with that much current and not dissipate too much heat while switching. The more you derate the MOSFET the less heatsinking it would need.

A quick look on Digikey gave a possible match of PSMN022-30PL - 30V, 30A, 27mΩ (typ) at 4.5V gate voltage.

simulate this circuit – Schematic created using CircuitLab


Use MQ2 Sensor with Arduino Uno without breadboard? I want to make a small and compact gas sensor using the Arduino Uno and MQ2 sensor. However all sites list a breadboard as a requirement.

Now, the MQ2 has A0, D0, GND, VCC, pins and the Uno also has A0, GND, 3.3V and 5V connectors.

So can I use Male to Female Jumper Wires to directly connect these? I am not using anything else like LEDs or speakers.

My code keeps the inbuilt LED ON when smoke level is LOW and blinks when the Level is HIGH. Also will I need any resistor for it?

This is point-to-point wiring, a technique loved by high-end audio amplifier fans:


Issues with reading numbers from serial port I've built 2 motor drivers for a robotics project and need to set positions that I want the motors to move to, and read that using the arduino. The arduino then uses a rotary encoder to implement a closed loop PID controller and move the motor the set point. My code wasn't working so I started troubleshooting and found out that my setpoint was getting reset to 0 automatically!

The only thin that changes the setpoint was the serial read so I made a smaller sketch for troubleshooting which is this:

volatile long setpoint;

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

void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

The result was quite odd, it sets the value correctly but resets back to 0 without me sending any new commands!

I tried updating the IDE to 1.8.12, tried old and new arduinos (with old and new bootloader) but all had the same result. Here is a demo video showing the weird reset to 0 problem:

https://streamable.com/kfgv61

I tried changing the buadrate higher or lower but that also didn't fix anything. Any ideas on what I'm doing wrong?

The problem here is that Serial.parseInt() stops when it sees the
newline, but it does not consume that newline, which is left in the
input buffer. Thus, at the next loop iteration, Serial.available()
returns true because of this newline and, unless you send another value
fast enough, Serial.parseInt() times out and returns zero.

The easy fix is to consume that newline yourself:

void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    if (Serial.peek() == '\n') Serial.read();  // consume LF
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

I personally would not use Serial.parseInt() at all, and would buffer
the data myself until I see the '\n'. This way there are
no surprises with timeouts being read as zero.


Maintain constant PWM voltage with changing Vcc I am making an arduino project with a single lithium ion battery, and want to be able to maintain a constant PWM voltage, even when the battery goes from 4.2-3.2v. I have been able to read the Vcc using the internal 1.1v reference, so I am wondering if I can make some sort of feedback system to increase the duty cycle when the battery discharges, in order to keep the same average voltage on the PWM. I want to be able to make it 3.2v constant, which should be attainable on Vcc from 4.2-3.2, with 100% duty cycle when the battery is at 3.2v.


Distance Sensor. Calculating running median and Average I'm trying to smooth out values for my IR distance sensor through running median filtering and a running average. I've tried to do the averaging, but my values don't seem correct and I am confused about how I would do the median filtering. I am also using timer interrupts and I don't want to use libraries when calculating the average and median. I've attached the code where I attempted to calculate the average.

int analogpin=5;
int sum=0;
int index=0;
int averead=0;
const int numreadings=9;
int i;
int timer1_counter;
int adc_val;
int int_flag;
int int_array[9];
float V;

void setup() {

int_flag=0;

Serial.begin(9600);
pinMode(analogpin,OUTPUT);
for(i=0; i<=8; i++){
  int_array[i]=0;
}

noInterrupts();           //

  TCCR1A = 0;
  TCCR1B = 0;

timer1_counter = 59286;

  TCNT1 = timer1_counter;
  TCCR1B |= (1 << CS12);
  TIMSK1 |= (1 << TOIE1);
  interrupts();
}

ISR(TIMER1_OVF_vect)
{
  TCNT1 = timer1_counter;
  int_flag=1;
    }

void loop() {

  if (int_flag==1){
    adc_val=analogRead(A2);
    V=5.0*adc_val/1023.0;
    analogWrite(analogpin,adc_val/4);
    }
    sum=sum-int_array[i];
    int_array[i]=analogRead(A2);
    sum=sum+int_array[i];
    index=index++;
    if(i==9){
      i=0;
    }
    averead=sum/numreadings;
    Serial.print("\n"); Serial.print("Average Filter Reading: ");
Serial.println(averead);
    delay(1);
    }

There are two main problems with your program. The first is noted in
Gerben's comment: you (attempt to) increment index (with a bad
syntax), while you should be incrementing i instead. The second
problem is these lines:

for (i = 0; i <= 8; i++) {
    int_array[i] = 0;
}

Fix the index vs. i confusion, remove the lines above, and your
program should work.

Explanation: The first point should be obvious, I hope. I am
discussing here the second issue. At the end of the loop above, the
index i has the value 9. Later, in loop(), and assuming you fixed
the first issue, the program does

i++;
if (i == 9) {
    i = 0;
}

and i has the value 10. From there i will continue incrementing, and
you are always writing outside of the array.

The root of the problem is that you used the same variable i for two
different purposes. There are several solutions to this:

use different variable names for different purposes
use local variables whenever applicable (here: in setup())
be defensive in your tests: instead of if (i == 9) write
if (i >= 9), but note that this alleviates but does not completely
solve the problem
remove the initialization of the array altogether.

I suggest removing the initialization because the array is a global
variable and, per the C++ standard, if not explicitly initialized it is
implicitly initialized to zero, so your initialization is redundant.


What type of sensor could I use to determine the mass of a small object (under 1 kg)? I'm building a robot that needs to pick up a piece of material and then determine its mass. My robot will retrieve the material using a scoop at the ended of a mechanized arm. Once the material is in the scoop, the arm will tilt upwards until the material slides down the arm and into the chassis.
I hope to weigh the material while its in the chassis, but I'm not sure how to do this. I've found that load sensors are useful for taking masses, but I'm not clear on how they're implemented. For example, I've found load beam cells, but how would I implement one in my design? Does it require a metal plate of some sort (like a weighing pan) on top of it like a laboratory scale? The sensor must be able to communicate with an Arduino.

My robot needs to be under 6 lbs and have a footprint of 35 x 35 cm. Thanks!

Just a little brainstorming:

If you have a spring, then you can easily calculate the physical force (mass) needed to stretch the spring to a certain extent. The law is called:
 Hookes's Law
 - you could then just measure the increase in distance between the initial position and the position with load. Use a servo or any distance measure.


Arduino IDE not handling library code correctly? The author of the PinChangeInt library and the EnableInterrupt library states at github:

  When the PinChangeInt was in a .h and .cpp file, the Arduino IDE tried
  to compile it twice. I have a technique that you can use- #define
  LIBCALL_ENABLEINTERRUPT - that if you put it ahead of your #include in
  all files but the sketch, then you should be able to use the library
  without conflicts. If you know how to make it work in another way-
  remember, this is a library and will not compile in the same directory
  as the sketch and any other .h/.cpp/.ino files- then I'm all ears.

I came there, because both libraries failed to build with linker errors due to double definitions. So far so good. I split the PinChangeInt library in .h and .cpp myself and it compiled flawlessly. I did not try to split the other library yet because it looks like much work to me.

So now my question(s): Is GreyGnome right with his statement, that library code gets compiled twice when split in code and headers? And if so, what are the consequences? Memory waste? Runtime errors? What about the many other (working) libraries exhibiting separate code and header files?

Header files are parsed by the preprocessor and the compiler wherever they are included.

There's nothing weird about that.
One can avoid multiple inclusions by using header guards.
That's pretty standard too.

I have not looked at the library, but, for example,  a typical error is to not declare variables as extern in the header and instead leave the real declaration in the header, which will lead to multiple instances, possibly clashing at link time.
Variables that are part of the library API should be declared as extern in the header and the real declaration should be done only in the .C/.CPP file.

Interrupts are an even more special case: the AVR gcc relies on very specific names to identify interrupt handlers and each of them can be present at most once.
So there are even more chances for having linker problems, if not declared correctly.


I can send on software serial, but not read? I've been cracking my head over this for a long while.

Like many before me, I'm trying to send and receive data from a HM-10 bluetooth module, arduino mega adk and the app called BLE Scanner. I've figured out receiving alright. Whatever I write into the serial monitor, shows up on the app. Whatever I write into the software serial, shows up. However, I haven't figured out how to read from the software serial. The available function never gets triggered, and always printing out the software serial read is always -1

The app supports sending data over bluetooth as well. However, using:

    #include <SoftwareSerial.h>
SoftwareSerial blueSerial(14, 15); //RX, TX
  blueSerial.begin(9600);
  Serial.begin(9600);
while (1)
  {
    blueSerial.listen();
    if (Serial.available()) {
      Serial.println("Writing");
      blueSerial.write(Serial.read());
      Serial.println(Serial.read());
      Serial.println(blueSerial.available());
    }
    if (blueSerial.available()) {
      Serial.println("Blueserial writing");
      Serial.write(blueSerial.read());
    }
}

The listen function is used out of pure desperation.

How do I fix this? This should be working right? Since I want to be sending AT commands to the bluetooth modules at some time and read their output, getting this to work is really important.

Possibly the built-in UART (Hardware Serial) assigned to the same pins is interfering with SoftwareSerial? If you really want to us SoftwareSerial, try it on a pair of pins that has no hardware UART attached.

And/or try SoftwareSerial (again, on a non-UART pair of pins) to connect to your PC (after uploading; you can't upload with it), and use Serial1 to connect to your device. This isn't the recommended or easiest way but it might help debug the problems you're seeing.


changing analog pins data logging using sdFat library Background:

My goal is to use sdFat library, more precisely AnalogBinLogger example.

I want to log data from changing analog pins for example, I want to log from pin 0 to pin 3 for 5 minutes and then from pin 4 to pin 6 for another 5 mins and then from pin 7 to pin 9 for another 5 mins. that is going to be continuously which means I am going to get rid of the part where you have to enter "r" to start logging.

Regarding the time, I managed to figure it out, I am just using the value of the variable count, if my sampling rate is 1000 samples/sec for example then 5 minutes will be 1000*60*5 and the change will be done in this line:

if (Serial.available()) {
  // Stop ISR calls.
  adcStop();

to

if (count >1000*60*5) {
  // Stop ISR calls.
  adcStop();

and this worked fine.

My problem is with the changing pins:

const uint8_t PIN_LIST[] = {1};

I changed this line to

uint8_t PIN_LIST[3] = {};

First I removed the word const, because it's not going to be constant anymore, and I just declared an empty array, and second I am changing the pins in the loop.

Here is the loop after I got rid of doing the serial input:

void loop(void) {
int i;
for (i=0;i<=12;i+3)
{
  PIN_LIST[] = {i,i+1,i+2};
  logData();
  Serial.println("done");
 }}

The problem is I get this error :

AnalogBinLogger.ino: In function 'void loop()':
AnalogBinLogger:808: error: expected primary-expression before ']'
token
AnalogBinLogger:808: error: expected primary-expression before '{'
token
AnalogBinLogger:808: error: expected `;' before '{' token

The line 808 is:

PIN_LIST[] = {i,i+1,i+2};

So this is the only error, any help please?

The code is so long (800+ lines) if this information is not enough and you need me to explain a part then just tell me.

in case someone has the same problem
it seems like after you initialize an array this way

uint8_t PIN_LIST[3] = {};

you won't be able to assign all the values at once:

PIN_LIST[] = {i,i+1,i+2};
instead you assign each individual value

PIN_LIST[0] = i;
PIN_LIST[1] = i+1;
PIN_LIST[2] = i+2;

and now it worked : )


How can Arduino's 8 bit Microcontrollers handle C++ I have just started getting into Arduino and c++ programming!

For all the talk on the internet about c++ being incompatible with 8-bit and even 16-bit microcontrollers, how is it that Arduino Microcontrollers can safely handle c++ code, in terms of the ram usage? Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) that (I believe) are very ram-usage-intensive?

Cheers!

It's a misconception that using constructors or C++ in general requires lots of RAM. Plus, to be clear, the AVR processors like the Micro and Uno have separate RAM and PROGMEM (program memory). So, code for functions does not, in itself, use RAM.

As an example, this small program for the Micro:

int main ()
  {
  }

That uses only 206 bytes of PROGMEM and 0 bytes of RAM (according to the IDE).

Sketch uses 206 bytes (0%) of program storage space. Maximum is 28,672 bytes.
Global variables use 0 bytes (0%) of dynamic memory, leaving 2,560 bytes for local variables. Maximum is 2,560 bytes.

Adding in a class, with a constructor, and using that class, increases the memory a bit:

class foo
  {
  public:
  int bar;  // some class variable

  foo ()  // constructor
    {
    bar = 1;
    }
  };  // end of foo

foo nick;  // a global variable
int main ()
  {
  PORTD = nick.bar;
  }

That uses 2 bytes of RAM, and 278 bytes of PROGMEM. Hardly a lot.

Sketch uses 278 bytes (0%) of program storage space. Maximum is 28,672 bytes.
Global variables use 2 bytes (0%) of dynamic memory, leaving 2,558 bytes for local variables. Maximum is 2,560 bytes.

Of course, the more things you do, the more RAM and PROGMEM it takes, however the compiler generates quite efficient code, and the linker strips out things that are not needed by your code.

  Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) ...

A lot of libraries use classes and constructors (for example the Serial library, the Print class, and a lot of others). There is nothing inherently RAM-intensive about a constructor. It's just a function that does something, with an implied this pointer to the current instance of the class.

  do lambdas work? (from a comment)

Yes you can use lambdas:

// array of function pointers
void (*doActionsArray []) () =
 {
 [] { Serial.println (0); } ,
 [] { Serial.println (1); } ,
 [] { Serial.println (2); } ,
 [] { Serial.println (3); } ,
 [] { Serial.println (4); } ,
 };

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

  doActionsArray [3] ();
  }  // end of setup

void loop () { }

  as long as you don't (extensively) use: the standard library, exceptions, templates ... (from a comment)

Templates can certainly simplify doing things like writing to, or reading from EEPROM and similar. For example:

#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

The standard library? There are implementations for the Arduino. We have to bear in mind that RAM is limited, however if you are going to do something anyway that involves linked lists, etc. then the Standard Template Library will probably do what you want as efficiently as you could if you coded it "by hand".

The bottom line is you need to be aware of what you are coding on. I have seen examples like this:

float foo [1000];  // hold my readings

That blows the available RAM on a Uno straight away. Nothing to do with C++ per se.

The other thing to be aware of is some tricks you can usefully employ. One common one is to replace:

Serial.println ("Program starting.");

With:

Serial.println (F("Program starting."));

The first example causes the compiler to copy the string "Program starting." from PROGMEM into RAM, using some of your valuable RAM. The second example doesn't.


Why does this method return an unprintable character, how do I convert it to display correctly? Page 14 says that the method should return the value 'h17'

typedef struct  {
  uint8_t data;
  uint8_t timestamp;
  unsigned char crc;
} tData;

int main(void)
{
  unsigned char* tempData = "snap";

    for(;;)
    {
      tData payload;
      payload.crc = crc8(tempData,sizeof(tempData));
      UDR0 = payload.crc;
    }

    return 0;
}

Because “h17” is an unprintable character, namely ASCII ETB. The 'h' in “h17” stands for “hexadecimal”, like the 0x usually used in C.

You should convert the value to an ASCII number if you want to print it, using for example Serial.print(payload.crc, 16); or – if you are not using Arduino core – (s)printf().

Edit: here is an implementation of my comment “sprintf() into a
buffer and dump the buffer to UDR0 one byte at a time”:

#include <stdio.h>

void print_byte_in_hex(uint8_t byte)
{
    // Print the byte in ASCII into an internal buffer.
    char buffer[8];
    sprintf(buffer, "%02x\r\n", byte);

    // Send it one byte at a time through the USART.
    for (char * p = buffer; *p; p++) {
        loop_until_bit_is_set(UCSR0A, UDRE0);
        UDR0 = *p;
    }
}


Which IDE should I use to write Pythonic-programs for Arduino I'm doing my first baby-steps to build tools using Arduino. I'd like to know if there is a way to write python scripts to build programs for Arduino. Most of IDEs I found are non-supported IDEs. Is there any "recommended" IDEs that I should use.

The recommended IDE for writing C/C++ for Arduino for beginners is the formal Arduino IDE, of which you can read more on the arduino.cc website.

Python is an interpreter language, and as such, require an interpreter running on the target machine. Unfortunately, the Arduino does not natively support running an Python interpreter, although some efforts has been made in that direction, for example the Python on a chip project, or the Python Arduino Proto API v2.
See this SO question for more details. If you go with any of these options, the IDE you would use would be your favorite Python IDE.

Note that both projects have their downsides, and actually there is no real alternative equivalent to running compiled C/C++ code on the Arduino. If you have strong Python programming abilities, this shouldn't be too hard for you as well :)


Usage of Crypto Library (Speck) I really want to understand how can I use this library for my purposes.

I'm trying to encrypt a message that comes through the serial port of the Arduino, and send it through another serial port. But I'm having issues understanding how to use the library.
I have read the documentation of the library, but I still get errors, I need a little help with this.

This is the code I have (without involving the serial ports), initially I wanted to check if I could define my strings and use them in another way instead of using the TestVector Function:

 #include <Crypto.h>
 #include <Speck.h>
 #include <SpeckSmall.h>
 #include <SpeckTiny.h>
 #include <string.h>

 struct EncryptText
 {
     const char *name;
     byte key[32];
     byte plaintext[16];
     byte ciphertext[16];
 };

 EncryptText test ;

   static TestCipher {

   test.name = "Speck-128-ECB";
   test.key = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                     0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
   test.plaintext = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                     0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
  test.ciphertext = {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                     0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};
   }

Speck speck;
SpeckSmall speckSmall;
SpeckTiny speckTiny;

byte buffer[16];

//void testCipher(BlockCipher *cipher, const struct TestVector *test, size_t keySize, bool decryption = true)
void testCipher(BlockCipher *cipher, size_t keySize, bool decryption = true)

{

    Serial.print(" Encryption ... ");
    cipher->setKey(key, keySize);
    cipher->encryptBlock(buffer, plaintext);

    for(byte b=0; b<16; b++)
   {
      Serial.print(buffer[b], HEX);
   }

    if (memcmp(buffer, ciphertext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");

    if (!decryption)
        return;

    Serial.print(" Decryption ... ");
    cipher->decryptBlock(buffer, ciphertext);

    for(byte b=0; b<16; b++)
   {
      Serial.print(buffer[b], HEX);
   }
    if (memcmp(buffer, plaintext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");
}

I'm getting the error: "exit status 1 'TestCipher' does not name a type"

EDIT: The full error that I get is:

 Speck_4-08-2017:27: error: 'TestCipher' does not name a type    static
 TestCipher {
           ^ Speck_4-08-2017.ino: In function 'void testCipher(BlockCipher*, size_t, bool)': Speck_4-08-2017:62: error:
 'key' was not declared in this scope
      cipher->setKey(key, keySize);
                     ^ Speck_4-08-2017:63: error: 'plaintext' was not declared in this scope
      cipher->encryptBlock(buffer, plaintext);
                                   ^ Speck_4-08-2017:70: error: 'ciphertext' was not declared in this scope
      if (memcmp(buffer, ciphertext, 16) == 0)
                         ^ Speck_4-08-2017:80: error: 'ciphertext' was not declared in this scope
      cipher->decryptBlock(buffer, ciphertext);
                                   ^ Speck_4-08-2017.ino: In function 'void perfCipher(BlockCipher*, const TestVector*, size_t, bool)':
 Speck_4-08-2017:104: error: 'key2' was not declared in this scope
          cipher->setKey(key2, keySize);
                         ^ Speck_4-08-2017.ino: In function 'void setup()': Speck_4-08-2017:158: error: 'testVectorSpeck128' was not
 declared in this scope
      testCipher(&speck, &testVectorSpeck128, 16);
                          ^ exit status 1 'TestCipher' does not name a type

Any guidance would be very helpful.

It looks like you want to create a struct and initialize it. Like this:

struct EncryptText
{
    const char *name;
    byte key[32];
    byte plaintext[16];
    byte ciphertext[16];
};

EncryptText test = {
    "Speck-128-ECB",
    {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                     0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                     0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
    {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                     0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18}
};

Then it appears you want to use that object. Note that to access each member of the struct you have to use dot notation (ex: test.key):

void testCipher(BlockCipher *cipher, size_t keySize, bool decryption = true)
{
    Serial.print(" Encryption ... ");
    cipher->setKey(test.key, keySize);
    cipher->encryptBlock(buffer, test.plaintext);

    for(byte b=0; b<16; b++)
    {
        Serial.print(buffer[b], HEX);
    }

    if (memcmp(buffer, test.ciphertext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");

    if (!decryption)
        return;

    Serial.print(" Decryption ... ");
    cipher->decryptBlock(buffer, test.ciphertext);

    for(byte b=0; b<16; b++)
    {
        Serial.print(buffer[b], HEX);
    }
    if (memcmp(buffer, test.plaintext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");
}


How can I pass multiple variables to a function? Using the FastLED library, I want to light up multiple lights at once.

Currently I am passing in just one light to the function.

spell( int LEDNumber )
{
  FastLED.clear();
  leds[LEDNumber] = CRGB (255,255,255); //white
  FastLED.show();
  time = 500;
  delay(t);
}

I would like to pass in more than just 1 light at a time.

You may create a struct with "x" elements, one for each LED:

struct ArrayOfBooleans {
   bool array[4];
};

ArrayOfBooleans myOutputArray;
myOutputArray.array[0] = true;
myOutputArray.array[1] = true;
myOutputArray.array[2] = false;
myOutputArray.array[3] = true;

lightEmUp(myOutputArray);

void lightEmUp(ArrayOfBooleans myOutputArray) {
   bool isFirstLightOn = myOutputArray.array[0];
   // etc
}

NoTE: If you run into Exception 9 issues (using this logic on another board), please check this answer to another post


ESP8266 ASCII to HEX convertion and checking I am trying to convert ASCII to hex and check if the hex is equal to that hex that I want.

For example:

1B 42 05 it means B in ASCII, I need to check if that hex is equal to 1B 42 05.

Here I need to send converted hex code from ASCII code by using SoftwareSerial.

Example:

02 20 2D 33 30 32 35 30 20 6B 67 0D 0A 03

I have to convert to

-30250 kg

A little explanation about HEX and ASCII:

About HEX
Raw computer data consists of zeros and ones. For humans it is difficult to read a (long) row of zeros and ones. You can represent such a row (of a certain length) by a decimal number, but then the relation with the underlying bits is not directly clear. For this reason the hexadecimal (HEX) representation is used (hexadeca comes from Greek and means 16.
Four bits can represent 16 different situations (= 16 different combinations of zeros and ones). The HEX digit belonging to each combination is:
0000 = 0; 0001 = 1; 0010 = 2; 0011 = 3; 0100 = 4; 0101 = 5; 0110 = 6; 0111 = 7
1000 = 8; 1001 = 9; 1010 = A; 1011 = B; 1100 = C; 1101 = D; 1110 = E; 1111 = F
When you memorize these 16 cases (from which the first 10 are easy because it is juist binary counting), you know immediately which bit-pattern belongs to a hexadecimal number and vice versa. For example: the HEX value 5A = 01011010.

About ASCII
Computer data contain not only numbers, but also text. As the computer can only handle bits (zeros and/or ones) we have to decide how letters (characters) are presented by bit patterns. And preferably in a standardized way, in order that different computers can handle each others text. Unfortunately there is more than one standard, but one that is very much used is the ASCII standard (see: https://en.wikipedia.org/wiki/ASCII).
The ASCII standard uses 7 bits codes and defines not only characters but also 'control codes' e.g. for 'line feed' and 'carriage return'. Often these 7 bits are stored in one byte (with the leftmost 8th bit set to 0) and can than be represented by two HEX digits.

Without further information nobody can tell what a row of bits represents. That's one of the reasons datatypes are used. They tell us what the row of bits represents and how many bits (or bytes) are used for the representation.

So the HEX representation of your row of 3 bytes is "1B 42 05" and, when these are characters, could stand for (look at the ASCII table): "ESCAPE B ENQ". In which 'ESCAPE' and 'ENQ' are control codes which meaning depends on the communication protocol.
The second row (of 14 bytes) could stand for: "STX SPACE - 3 0 2 5 0 SPACE k g CR LF ETX". STX and ETX stand for 'START OF TEXT' and 'END OF TEXT'. 'LF' stands for 'LINE FEED' and 'CR'stands for 'CARRIAGE RETURN'.

I hope that with this explanation you have a better idea about HEX and ASCII and that you now will be able to figure out how to handle your data.


Erasing 1 byte of external Flash memory (winbond) i'm trying to use an external flash memory Winbond 25q64jvsiq for my Arduino Nano based project for audio recording purposes, to have extra memory for recording 1 byte audio samples, since Arduino nano SRAM memory is too small (8kb), to store at least 1 second of 8 kHz 8 bit samples audio. I'm trying to understand the basics of  bytes storing in my external memory. I'm using SPIMemory library for that, and i can't find a function to erase 1 byte, there is only sectorErase() function. So i wonder is it even possible to erase a single byte of external memory?
Here is a part of code where i try to rewrite (erase one byte and write a new one) a next byte when the button pressed, but when it erase a sector it erases not the one byte but all bytes behind it, and i want to manipulate it more accurate, and erase only one byte:
if(!digitalRead(5)){      //button pressed
     if(e<3){
      e++;
      flash.eraseSector(count);    //erasing a byte
      flash.writeByte(count,e,NOERRCHK); // write a new value
      }  else {
        e=0;
        flash.eraseSector(count);
        flash.writeByte(count,e,NOERRCHK);
        }
     }

For a flash chip, no it's not possible to erase a single byte.
The closest you can do is to read an entire sector into memory, erase that sector, modify your in-memory copy, then write the sector back.
You would be better using an SPI SRAM or PSRAM chip instead of a flash chip.


How do I read from /dev/ttyACM0 in Linux without a terminal emulator? I just bought an Arduino Due and I'm having trouble reading from a simple serial IO program.

I have a SparkFun RedBoard which is like an Uno. With that, I just ran a "stty" command to configure the baud rate and other terminal settings, and then I could do "cat /dev/ttyUSB0". Actually I have a C++ program which opens "/dev/ttyUSB01" and reads from it like a normal file.

Now, with the Due, the device is "/dev/ttyACM0" and there have been a few snags. One of them is that after programming the Due, and running stty, I have to open /dev/ttyACM0 using the screen program:

screen /dev/ttyACM0 115200

and then kill screen, before cat /dev/ttyACM0 will work. Otherwise, cat prints out one byte and exits; rarely it prints out 10 bytes or a line, or sometimes it prints nothing.

This is a bit annoying and I can't figure out what screen is doing to the device which I can't seem to accomplish using stty. My stty command is:

sudo stty -F /dev/ttyACM* 115200 -parenb -parodd -cmspar cs8 -hupcl -cstopb cread clocal -crtscts \
-ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl ixon -ixoff -iuclc \
-ixany -imaxbel -iutf8 \
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 \
-isig -icanon iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl \
echoke -flusho -extproc

I got this by running stty -a < /dev/ttyACM0 after using screen to initialize as above.

I thought it might have something to do with serial auto-reset, so I tried using a resistor between 3.3V and RESET, but this did not fix the problem.

I should note that cu from the uucp package is able to read continuously from /dev/ttyACM0, but unlike screen it does not leave the terminal set up in such a way that a subsequent cat command will work.

$ cu -l /dev/ttyACM0 -s 115200
<continuous stream of data>
$ killall cu             # (from another shell)
$ cat /dev/ttyACM0 | hexdump -c
<e.g. 7 bytes>
$

With screen, cat would have printed an infinite stream. Any ideas how to accomplish this setup without using screen?

I have had very similar problems with my yun(shields) and I found the stty command to be very crucial for a good working.
I use following command and it works with mega and due on the yun

stty -F ${PortName}  ${SerialSpeed}  raw -clocal -echo icrnl

Since I call these I can redirect from and to /dev/ttyxxx without problems.
As far as I can see you mis the raw.