How to connect IR Transmitter and Receiver Module? The IR Transmitter and Receiver module has both receiver and transmitter in same board. I tried Arduino IR Remote library example to decode Remote signal using below connection, but its not working.

IR MODULE:   ARDUINO
Ground   ->  Ground
5V       ->  5V
RXD      ->  PIN 11
TXD      ->  PIN 10

The board also has 3 pin connector (Gnd, 5v, S). How to connect pins to Arduino to receive/decode and send IR signals? (Can't able to find any tutorial for this type of board)

Example Code:

#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

The device in the question is commonly sold on aliexpress.com and the likes of ebay.com.  As you might guess there is little in the way of documentation.  Without documentation we can only speculate.  As such, I expect that the module handles all the modulation and demodulation.  It is likely all you need to do is use the Arduino serial library and connect the TX and RX to the Arduino's RX and TX pins.  However, if you would like to preserve the function of these pins for use with the Arduino Uno's USB port, you can use the Arduino software serial library which will "emulate" a serial port an an unused (alternate) set of pins.

(This is an example of a similar well documented device with access to the schematic and source code.  Armed with this type of knowledge you can turn this device into what ever you want.  In other words, you probably don't even need an Arduino.  You can just program this device and be done with your project.)


digitalRead influenced by touches const int BUTTON      = 8;

void setup() {
  Serial.begin(9600);
  pinMode(BUTTON, INPUT);
}

void loop() {

  Serial.println(digitalRead(BUTTON));

}

I have connected a cable to pin 8. It's not connected to anything else nor have I any other cables connected.
I am expecting constant zeros, but I keep getting ones and zeros all the time, e.g. when shortly touching the cable.

I didn't experience that before. Did I accidentally damage my Arduino?

The pin is floating. Use pull up or pull down to help define its logic state.


Data at Serial Port Avaliable I am interfacing a GSM modem via Arduino at Serial port 2.

I have seen that responses fron GSM modem are subject to time. Sometime its response are fast and sometime it are slow. I  have a code like below which checks for response from GSM modem based upon a user configurable timeout value:

sendATcommand(str_at_cmd, str_ok, 500);

int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout)
{
    uint8_t x=0;
    char response[100];
    unsigned long previous;
    int answer = 0;
    memset(response, '\0', 100);
    answer = 0;;
    delay(100);
    ClearSerialData(); // read and flush all data
    debug_println(ATcommand);
    Serial2.println(ATcommand);
    delay(200);
    x = 0;
    previous = millis();
    do {
       if(Serial2.available() > 0){
       response[x] = Serial2.read();
       delay(100);
       debug_print(response[x]);
       response[++x] = '\0';
       if (strstr(response, expected_answer) != NULL)
       {
           debug_print("\nAnswer Mathced");
           answer = 1;
       }
       }
    }while((answer == 0) && ((millis() - previous) < timeout));
    debug_println("\nReturning from AT Command");
    return answer;
}

I was never able to set the correct timeout value - as at random test it failed once or twice and not received 100% success.

My question if I change the code like below

while(Serial2.available() > 0){
   response[x] = Serial2.read();
   delay(100);
   debug_print(response[x]);
   response[++x] = '\0';
   if (strstr(response, expected_answer) != NULL)
   {
       debug_print("\nAnswer Mathced");
       answer = 1;
   }
}

So when does Serial2.available() method returns <= 0 value. Is my above code correct - this way I overcome the timeout issue and all my GSM responses are being read - are there scenarios that I will end up in infinite loop?

Your code is flawed in that you are waiting a fixed time, and then hoping that the entire response will arrive quickly. Personally I would send the query, and then exit the function. Test for incoming data in your main loop, and process it when it is all received. Techniques described here: http://www.gammon.com.au/serial

The whole thing should be able to be written without delay().


Is it possible to setup a CAN-BUS Arduino Shield to communicate with SocketCAN for UNIX? I have an Arduino + SparkFun CAN shield, and I was hoping to set it up to work with candump on an Ubuntu system. Is this doable, or is candump made specifically for raspberry Pi's?

Yes. Normally you would write a linux kernel driver to communicate with your device (arduino) following your own protocol, but SocketCAN provides by default a way to interface with Lawicel dongles, whose communication protocol is publicly available: CANUSB / CAN232 protocol.

Many people have built arduino sketches that implement this protocol so you can use your arduino with SocketCAN in Linux (candump, cansniff...) as if it were a Lawicel dongle.

You may find this useful:

https://github.com/autowp/arduino-canhacker

https://github.com/kahiroka/slcanuino


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

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

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

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

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

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

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

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

I ran across this post and thought that a more in depth explanation should be given on why when using digital inputs that more times than not you will need to use the pull-up resistors.

When you define one of the pins to be a input the chip measures the voltage on the pins, if the voltage measures more than half of the VCC voltage the input is off. What happens if you don't use a Pull-up Resistor the chip will measure a seemingly random voltage. This is because of interference from other electronics, radio waves etc.

So what happens when you use a high resistance Resistor (10 - 100 ohms) it forces the voltage to remain high if the pin is not grounded since there is voltage being applied. But when you ground the pin using a Button or whatever the pin is kept under the halfway mark around 0V.

As you mentioned using the code:

pinMode(PIN, INPUT_PULLUP);

enables the internal Pull-Up Resistors in the chip by setting the Pin to a High state like you would defining it as a output. The code above is a newer way of writing:

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

Now there is another reason for seemingly random input signals, which is called "Button Bounce". What happens here is when a User presses the Button there might be a very small time that the Button actually connects then disconnects then finally reconnects. This is because of when the contacts of the Switch come together sometimes they don't connect perfectly, one side of the Switch might connect then be disconnected as the connecting plate levels out before finally connecting as it should.

Below is a Snapshot I found from http://www.gammon.com.au, it shows a bounce from a Osillicope showing the actual Button Bounce:

To make sure that the user is actually pressing the button use a delay and recheck the Button again to see if it is still pressed. I find that a 500 - 700 microsecond delay works great. I provided a quick example on how to catch a Button Bounce (https://www.arduino.cc):

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

I hope that this explanation will help others out saving them from banging their heads against the wall trying to figure out where these phantom signals are coming from.


Binary to decimal using bitwise operators I am trying to convert some binary data to decimal numbers. I succeeded to convert binary to hex, but now I want to do the same with binary to decimal. I want to use bitwise operators and NO array.

See my code from binairy to hex. The incoming data is 8 bits. This code first calculates the most significant number, and then, the least significant number. This works good, but I cannot figure it out for bin to dec

The function console_print_char is sort of the printf function of my program.

    void console_print_hex_char(unsigned char data){
    unsigned char temp;

    if(data){
        temp = (data >> 4);
        if(temp){
            if(temp> 9) console_print_char(temp + ('A'- 10));
            else console_print_char(temp + '0');
        }
        temp = data & 0x0F;
        if(temp> 9) console_print_char(temp + ('A'- 10));
        else console_print_char(temp + '0');
    }
    else{
        console_print_char('0');
    }
}

You cannot do what you are trying to do. There is no direct correspondence between some number of bits and a decimal digit.

With hexadecimal, every 4 bits corresponds to exactly 1 hex digit. That is why hex is used for computers.

One hex digit represents exactly 4 bits. Every time you add another hex digit, you add 4 bits.

Two hex digits corresponds to exactly a byte. 00h to FFh represents a value from 0 to 255.

There is no such direct correspondence between binary and decimal. If you have 4 bits, it takes 1 or 2 decimal digits to represent it (0-15) If you have 8 bits, it takes 1, 2, or 3 decimal digits to represent it, but there are 3 digit decimal values (values > 255) that you can't represent with 8 bits.

Binary  Hex Decimal
0000    0   0
0001    1   1
0010    2   2
0011    3   3
0100    4   4
0101    5   5
0110    6   6
0111    7   7
1000    8   8
1001    9   9
1010    A   10
1011    B   11
1100    C   12
1101    D   13
1110    E   14
1111    F   15

You simply cannot convert a binary number to decimal using bit shifting and masking.

As @Kwasmich says in their answer, the closest you're likely to come would be to convert your binary value to BCD (Binary coded decimal) where each 4 bits holds a decimal digit. You could convert THAT to decimal character output using masking and shifting.


Can an Arduino emulate a USB mass storage device? Question:

Can I connect an Arduino's USB port to the USB port of another embedded device that is expecting a USB thumb/flash device?

Or, can I connect a USB module to this embedded device, with the other end connected to GPIO's of the Arduino?

This embedded USB thumb device requires a thumb drive to transfer a file. I need to emulate the connection, disconnection, and thumb drive with the folder and file with a Arduino.

Is it possible to emulate an USB thumb drive between an Arduino and an embedded device's USB port?

Research:

I saw a couple other questions that talk about USB being a master/slave configuration and that certain IC are required. Additionally, that there were some cables that can be used for two-way data transfer (mostly for PC to PC data transfers). If that is the case, could one of those cables be used for this configuration? Which cable would work?

Possible Solution:

The embedded device I need to emulate a thumb drive on will automatically search for the file in a specific folder of the thumb drive. Would I be able to partition a section of an SD card with the SD card module to appear as a thumb drive, and then connect that partition to the embedded device via USB-A to USB-A cable?

Diagram:

Arduino USB Port -> USB Cable -> Embedded Device USB Port
Arduino GPIO -> USB Module -> USB Cable -> Embedded Device USB Port

Requirements:

Connection via USB cable between Arduino and an embedded device's USB port.
Ability to emulate the connection and disconnection of a USB thumb drive on the embedded device.

The description of this device from Sparkfun appears to match the OP's requirement for integrating an Arduino with other USB devices by enabling the Arduino to acts as a USB host. https://www.sparkfun.com/products/9947


Arduino and visual basic Serial data I am trying to send command serially through Vb.through serial monitor working fine . But Through VB it not detecting port
My arduino code:

int ledPin = 2; // the number of the LED pin

void setup() {
Serial.begin(9600); // set serial speed
pinMode(ledPin, OUTPUT); // set LED as output
digitalWrite(ledPin, LOW); //turn off LED
}

void loop(){
while (Serial.available() == 0); // do nothing if nothing sent
int val = Serial.read() - '0'; // deduct ascii value of '0' to find numeric value of sent number

if (val == 1) { // test for command 1 then turn on LED
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // turn on LED
}
else if (val == 0) // test for command 0 then turn off LED
{
Serial.println("LED OFF");
digitalWrite(ledPin, LOW); // turn off LED
}
else // if not one of above command, do nothing
{
//val = val;
Serial.println("Wrong command");
}
Serial.println(val);
Serial.flush(); // clear serial port
}

VB Code

Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Public Class Form1
    Shared _continue As Boolean

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        SerialPort1.Open()
        SerialPort1.PortName = "COM3"

        SerialPort1.BaudRate = 9600
        SerialPort1.DataBits = 8
        SerialPort1.Parity = IO.Ports.Parity.None
        SerialPort1.StopBits = IO.Ports.StopBits.One
        SerialPort1.Handshake = IO.Ports.Handshake.None
        SerialPort1.Encoding = System.Text.Encoding.Default 'very important!

    End Sub

    Private Sub Button1_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1_Click.Click
        SerialPort1.Open()
        SerialPort1.Write("1")
        SerialPort1.Close()
    End Sub

    Private Sub Button2_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2_Click.Click
        SerialPort1.Open()
        SerialPort1.Write("0")
        SerialPort1.Close()
    End Sub

End Class

Error I am getting .Arduino port is 3. and configured to port 3 . i dont know why it giving error.

The port 'com10' does not exist.

This Line added as you said

Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SerialPort1.Open()
        Dim str As String
        str = SerialPort1.ReadExisting
        Current_Read.Text = str
        SerialPort1.Close()
    End Sub

This is working But data not being updating

Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Current_Read.Text =SerialPort1.ReadLine
    End Sub

You've opened the port before you've configured it.


Converting Arduino LCD Programs to Serial I2C LCD code I just got a Serial LCD and wanted to test it out with a game. I found this site with game conversions and wanted to use this game.  However since my serial LCD use the LiquidCrystalic2 library the code in its current state won't work. Is there a simple method of converting or porting liquidcrystal to LiquidCrystalic2? Or if someone knows of a simple game in regards to hardware that uses a serial lcd and could direct me to a link that would be great.

i got my lcd working on I2C following the steps in this link http://forum.arduino.cc/index.php?topic=128635.0


Need help with 2X3 matrix for braille I'm an intermediate Arduino progammer, and I'm making an electronic braille display for my friend. You can think of this display as an array of 28x3 LEDs(one braille character contains a maximum of six (2x3 for one letter) dots so there can be 14 characters displayed at a time, including spaces) but actually instead of LEDs, there will be electrical braille cells. This will be the algorithm:

Read string (English alphabet) files from SD card
Count the letters, including spaces, until it becomes 14. Convert them into braille (2x3 for one letter) and then display them (as we will be able to display only 14 letters at a time )
When the user presses the button for the next row/page do the same process(step 2) for the next string.

So this is the complete process I want to do.

I have 5 months deadline to make it. The main problem is how I can make the code to convert and then display it. I know there are already a lot of Arduino libraries out there for displaying stranded English characters, but this is different, because I'm new to Arduino and 'C'.

Instead of losing your mind and saying this site is not for fool people like you, please guide this 17yr old what should I learn in order to make this for my friend who lost his eyesight in an accident(consider I have time of 5 months).

Do I have to build entire new Library for converting alphabet and multiplexing braille? Or is there existing code that will work.

Each character will be 6 bits (so let's use a byte to store it) and we'll use the following bit to LED mapping

bit0   bit1
bit2   bit3
bit4   bit5

Now you just need an array of bytes where each byte signifies an ASCII character.
Your code will get the letters to display and for each one will do something like this:

byte BrailleBytes[] = {0x01, 0x05, 0xD, etc etc}; // only done the first 3 chars

byte getBrailleForCharacter(char c)
{
    int index = asc(c) - asc('A');
    return BrailleBytes[index];
}

The key to decoding it this way is to make sure you sequence your bytes in BrailleByte the same way the ASCII table does - so if you want punctuation/numbers etc then you'll have to start lower and adjust the asc('A') accordingly

Now you have the byte it is just a case of checking what bits are set and turning on the relavant LEDs.


How is stack memory used for fuctions and local variables? I wanted to save some values to the EEPROM and also wanted to free up SRAM by avoiding some variable declarations, but EEPROM memory is byte wise.

If I want to store an int value, I have to use some expressions repeatedly. I thought I would make some functions for those. But I am concerned that, if I create a function, it would still occupy SRAM memory, better I declare an int variable instead of using EEPROM.

How are the functions and the local variables stored in SRAM? Does it only store the address of the fuction pointer from the flash memory or all the variables and commands are stored on the stack?

Local variables and function parameters are stored on the stack. However, that is not a reason not to use them. Computers are designed to work that way.

Stack memory is only in use while a function is active. As soon as the function returns, the memory is freed. Stack memory is a GOOD Thing.

You don't want to use recursive functions with lots of levels of recursion, or allocate lots of large structures on the stack. Normal use is fine however.

The 6502 stack is only 256 bytes, but the Apple II works just fine.


Need help figuring out the pinout of a seven segmented display A friend of mine gave me a 2in. 4 digit seven segment display. But when I sat down and looked at it, I found it has 7 pins on one side and 5 on the other and no indicators of its pinout on it. The only information I could gleam from it was the (presumably its model number) which said "PARA LIGHT A-5V4G-12-U1 H H0615". I searched online for it but only found ambiguous information that didn't help me. I have a feeling this is a fairly easy question, if so: sorry I am a noob.

Without an image of the display, I'll have to guess. With 12 pins in total, what you most likely have is: 8 pins for 7 segments and the decimal point, and 4 COMMON anodes or cathodes, a detail you will have to discover yourself. This process requires a power source that can safely light LEDs. A multimeter in diode test mode will do since theres usually about 2 V across the probes and some internal resistance, enough to light up the LEDs in the display, though they wont be very bright. I will try to list the minimum number of steps needed to determine the pinout using this method.

Using a multimeter set to diode test mode, place the red probe on any pin (though its good to start at the edges). Now lazily run (i.e. make contact) the black probe through the remaining pins. If the display is a common anode display, you should see the all the segments of a particular digit (not different digits) light up in sequence.
Else, keep running the black probe through the pins until any segment at all lights up. Hold the black probe on that pin that caused the segment to turn on. Now run the red probe through the other pins. If all the segments of a particular digit light up in sequence, this indicates a common cathode display.
Another possibility is that no segment lights up at all, despite steps 1 & 2. Substitute the red probe, where it is held steady, for the black probe. Run the red probe through the remaining pins. If all the segments of a particular digit light up, then the display is a common cathode display.
On the other hand, if no digit's segments light up sequentially while running the red probe through the pins, but at least one segment of any digit lights up, then hold the red probe steady on its current pin, and run the black probe instead through the other pins. If all the segments of a digit light up in sequence, then you have a common anode display.

Take note of the pin that was held constant, in any of the cases above.

Now that you know what kind of display you have, you now need to discover the pinout for the segments and common anodes/cathodes. Get paper and pen so you can label each pin with its function. Create a table with pin numbers in one column (pin 1 - 12) and the pin functions (which you will find out) in the second column.

This image shows the segment labels. During the testing above, one
probe (PROBE A) was held steady on one pin while the other (PROBE B)
was run through the other pins. This caused all the segments of a
digit to turn on. The pin connected steadily to PROBE A is the COMMON pin for
the digit whose segments lit up. So in your table, Pin xx = COMMON
for Digit yy.
To get the COMMON for other digits, move PROBE A to another pin and
run PROBE B through the other pins until another digit has all its
segments turned on in sequence. The pin connected to PROBE A is the
COMMON for that digit. Include this in your table. Repeat until you
have identified the COMMON for each digit.
Finally to get the segment pins A - G and DP, place PROBE A on any of the COMMONs you have in your table and run PROBE B through the other pins. Each time a segment lights up, the pin connected to PROBE B should be associated with that segment's label in your table. E.g. if segment C lights up when PROBE B is on pin 10, then the table should have something like pin 10 = C. Keep going until you have all the segment pins identified.


Why does my LCD display random characters? I've been struggling with my LCD for hours, and after solving more different issues than I can remember, I'm out of ideas for this one.

My LCD is showing random characters, see the picture below (the last character blinks, some characters change and over time there are slowly more and more characters). I'm starting to wonder if the LCD I chose has a driver compatible with the LiquidCrystal library, what do you think? If so what can I do to avoid buying another one?

Here is the code:

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
//RS EN D4 D5 D6 D7
LiquidCrystal lcd(2, 3, 4, 5, A2, A3);
//RW to GND, VSS to GND, VCC to 5V, V0 to wiper of 5V-to-GND 10k potentiometer

void setup() {
  Serial.begin(9600);
  Serial.println("Starting");
  lcd.begin(16, 2);
}

void loop() {
  lcd.setCursor(0, 1);
  lcd.print(millis() / 1000);
  Serial.println("Printing");
  delay(1000);
}

I'm using this Arduino and this LCD. Note that I'm using pins 10,11,12,13 for a SD (which works) and 6 7 8 for a MAX232 (which is disabled).

Any ideas?

It could be because "millis()/1000" generates a "number", and not the "string" (or "char"). Try to add ",DEC" in your lcd.print(), something like "millis()/1000,DEC" to convert it to "decimal". Generally, it depends on the library, how they implement this function.

Good luck,

Mike


Deep sleep mode for the Uno without complicated circuits? so I'm building something using an Uno that will run on batteries - so, I've watched a couple of these low power tutorials to lessen the energy consumption so the batteries can last longer, but they're not exactly what I want - they all require some sort of circuit. I've found this tutorial (http://www.engblaze.com/hush-little-microprocessor-avr-and-arduino-sleep-mode-basics/) which only needs an LED, and it's ideal, but I would like to know if you know of any other methods which would reduce consumption to less than 5mA without using any complicated circuits (other than unplugging the Uno)

Thank you!

Deep sleep mode for the Uno without complicated circuits?

Forget using an Arduino Uno if you want to do low power (less than 10 mA standby). There is too much extra circuits (LEDs, Voltage Regulators, etc) to allow that.

See for instance, https://www.gammon.com.au/forum/?id=11497

With an Arduino Pro Mini it is possible to achieve low power after removing the Power LED and cutting the Voltage Regulator.

The hardware/software support for low power cannot really be used before the board is design for that.

Cheers!


Slave to Send Data after Receiving Command using I2C I want to have my Slave Arduino to send signal to Master after the command was made. But the Slave Arduino does not proceeds to sending the signal after doing the command. What is wrong with my code?

Slave

void receiveEvent(int bytes) {
  dir = Wire.read();    // direction
  dis = Wire.read();    // distance
  spe = Wire.read();    // speed
  eStop = Wire.read();    // 1 or 0
  Serial.println(dir);
  Serial.println(dis);
  Serial.println(spe);
  mov = true;
}
void loop() {
    Wire.onReceive(receiveEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
       Wire.onRequest(requestEvent);
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
      Wire.onRequest(requestEvent);
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}
void requestEvent(){
    Wire.write(1);
    fin = false;
    Serial.println("sent");
}

Master

#include <Wire.h>

const byte interruptPin = 2;
byte dir = 0;
byte dis;
byte spe;
bool upd;

bool state= false;

void setup() {

  Wire.begin();
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), emergencyStop, CHANGE);
  Serial.begin(9600);

}
void loop() {
       if( state == false ){
       dir = 1;
       dis = 30;
       spe = 2;
       Wire.beginTransmission(9); // transmit to device #9
       Wire.write(dir);
       Wire.write(dis);
       Wire.write(spe);
       Wire.write(0);
       Wire.endTransmission();    // stop transmitting
       state = true;
       }
       if (state == true){
        if(Wire.available() > 0){
       Wire.requestFrom(9,2);   //6bytes from slave 9
          bool upd = Wire.read();
          Serial.println(upd);
        }
      }
}
void emergencyStop(){ // not working
  Wire.beginTransmission(9); // transmit to device #9
       Wire.write(0);
       Wire.write(0);
       Wire.write(0);
       Wire.write(1);
       Wire.endTransmission();    // stop transmitting

}

found my solution for this. although not verified yet, but i removed Serial print and moved the Wire.onRequest outside of the if loop. and uses a ledPin for checkups

void loop() {

        Wire.onReceive(receiveEvent);
        Wire.onRequest(requestEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}

void requestEvent(){
    if ( fin == true){
      Wire.write(1);
     fin = false;
    digitalWrite(ledPin, HIGH);
    }

}


Arduino Uno programed from a Nvidia Jetson tx2 I'm trying to program my Arduino Uno with a Jetson tx2 and get the error

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

The serial port is set to /dev/ttyS0

dmesg when the Arduino is plugged in returns

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

lsusb returns

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

The version of the Arduino IDE contained in the Jetson repositories is buggy on the Jetson TX2 with Jetpack 3.2+ and the Arduino IDE in the repository is rather old.  Instead, try the beta related to Github Issue #7302.  This beta should work with the Jetson and other aarch64 platforms.  Many thanks to the wonderful people working to support this platform.
Steps
After downloading and unpackaging the build, perform the following steps:
#Install the OpenJDK Dependencies
sudo apt-get install openjdk-8-jre openjdk-8-jdk

#Remove the Packaged Java Folder
cd ${PATH}/arduino-PR-beta1.9-BUILD-69
sudo rm -r java

#Add armhf Architecture to Package Manager
sudo dpkg --add-architecture armhf
sudo apt-get update
sudo apt-get install libc6:armhf libstdc++6:armhf

#Install the Arduino IDE
sudo ./install.sh
sudo ./arduino-linux-setup.sh

#Reboot

Notes

The script arduino-linux-setup.sh handles the permissions for the IDE to talk to ttyACM0, updates the udev rules, and removes the pesky Modem Manger.
The armhf packages are necessay to prevent ctags from crashing.
If you are still having issues with CDC/ACM, install the module using the scripts from JetsonHacks


Arduino New Optiboot Bootloader on custom ATMega328p board, ATMEL Studio and AVRdude I am about to ask a kind of complex question due to the number of system parts involved and the system architecture I am planning to use.

First of all I have a tiny bit of experience with the Arduino Nano and a professional experience with C microcontroller programming.

What I would like is to create a custom ATMega328p board that does something and be able to update whatever firmware is running on it using the UART port.

1) Firmware updating

Since I am not so familiar with bootloaders, I would skip for now writing my own, so I would like to use the newest Arduino Bootloader for ATMega328p to support the firmware updates.

2) Custom program compilation

What I definitely do NOT want is use Arduino Sketch IDE to compile whatever application code. I am using Atmel Studio up to now for whatever bootloaderless applications I was doing and I would like to keep using that with my own project and code structure. The question here is, do I need to make any linker modifications or modifications in the code in Atmel Studio projects in order to be able to "transform" my code into application code so that can coexist with the bootloader?

3) Updated firmware programming

After the board is on the field running with the Optiboot bootloader and an outdated firmware, I would like to use a thirdparty software to communicate with the bootloader and update the application code. Since the optiboot bootloader used by Arduino uses the STK500 communication protocol and functionality, could I use AVRdude to communicate with the bootloader and flash the applications code only through UART?

Do you think this concept could work?

Thank you in advance.
polylogic

Since I am not so familiar with bootloaders, I would skip for now writing my own, so I would like to use the newest Arduino Bootloader for ATMega328p to support the firmware updates.

Even people who do know about bootloaders rarely bother writing their own when there is a perfectly good one with good support and good cross-platform tools available.  Why would you?

  The question here is, do I need to make any linker modifications or modifications in the code in Atmel Studio projects in order to be able to "transform" my code into application code so that can coexist with the bootloader?

No. The bootloader resides at a high memory address, and your code at address 0x0000 just like normal.  A fuse is set to say "Boot at the bootloader address", and another lets you set the size of the bootloader area (and thus the bootloader address).

  Since the optiboot bootloader used by Arduino uses the STK500 communication protocol and functionality, could I use AVRdude to communicate with the bootloader and flash the applications code only through UART?

Yes. This is what the Arduino IDE does. It just runs avrdude to communicate with the bootloader.  If you turn on verbose mode in the preferences you should be able to see what the exact command is that it runs so you can replicate it in your own program or script.


Decoding 2.4G RF remote controller? There is tons of information on how IR remote controls work and how to use an Arduino to decode those signals and use any IR remote to suit your project. But I couldn't find much info about 2.4G RF remotes.

I want to control a string of addressable LEDs and cycle through different patterns using one of these 2.4G RF remotes

Is it possible to use these remotes with Arduino? If yes, how can I read the signals and assign tasks to different buttons on the remote?

The usual approach for 2.4 GHz is to open the product, identify the radio chip, and use a USB logic analyzer on the SPI bus that usually connects it to the MCU to capture the configuration and data traffic, and figure out what the configuration register accesses mean from the radio chip data sheet.

The occasional appearance of combined MCU/radio parts prevents that approach, but often that is only used on one end of the link and the other will still have a distinct MCU and radio with an SPI bus in between.

This is heavily practiced in the radio control community, as people want to use their nice transmitters to fly cheap toys.  And there is code out there to transmit compatibly with some of the odder chips like the X297, using more common ones like the NRF24L01 or its workalikes from Beken, etc.

A key advantage of SPI sniffing versus over-the-air sniffing is that the usually implemented channel-hopping doesn't mean you loose the signal ever time it moves to a new channel - and you actually get to the see the frequency registers being written.  To capture a hopping scheme over the air, you would need something more like a spectrum analyzer to figure out the sequence, and then have software track the signal while you attempt to figure out the data.  However, a remote which only sends occasional button presses may not use hopping in the way something sending data continuously (like an R/C set, or possibly a keyboard/mouse) would.


Suggest some highly sensitive temperature sensor Currently I am using DHT11 in my project, but its not very sensitive, it is quite slow in detecting temperature changes.

What sensor could I use that will be more sensitive?

You can use the LM35, is a Precision Centigrade Temperature Sensors with TO-92 package or SO-8 SMD package.

Here is a tutorial of how to use.

Its very simple to use it.


Array of Strings and Callbacks I am trying to create an array of structs that contain pairs of Strings and Callbacks the problem I am having is assigning the callback function. I have the following code:

#define UI_ROUTINE_ITEMS 10

struct MenuItem{
    String label;
    typedef void (*callback)();
};

class MenuSystem{
   MenuItem routineMenu[UI_ROUTINE_ITEMS];

   MenuSystem(){
      routineMenu[0] = {"Test", &Test::TestCallback};
   }
}

class Test{
   void TestCallback(){
      Serial.println("Callback called");
   }
}

When I try to compile this I get:

error: no match for 'operator=' (operand types are 'MenuItem' and '<brace-enclosed initializer list>')

I know this is a Syntax issue I just can not figure out how this should be done. I have looked at several examples but I can't figure out how to do this with Classes without using free/malloc, what am I doing wrong?

EDIT

I finally got this working, the problem was that the function that I was trying to call was not static and the declaration in the structure was not quite right. Below is the corrected example:

#define UI_ROUTINE_ITEMS 10

#include <Arduino.h>

struct MenuItem{
    String label;
    void (*callback)(void);
};

class MenuSystem{
   MenuItem routineMenu[UI_ROUTINE_ITEMS];

   MenuSystem(){
      routineMenu[0] = {"Test", &Test::TestCallback};
   }
}

class Test{
   public static void TestCallback(){
      Serial.println("Callback called");
   }
}

Several issue with this code. First, use public/protected/private for classes. Second, use a const char* instead of String or even better str_P. It is the usage of String that is giving the compile error. Third, the Test::TestCallback function reference is not possible. It is a member function. To correct that either have an instance or define the callback function as static.

You could define an abstract MenuItem class with the string and a virtual member function. A Menu class would hold a collection of MenuItems. All the static data should be put in program memory.

There is a Menu system in Cosa. Please see the example sketch. This implementation follows the MVC design pattern.

Cheers!


Arduino Nano and 0.96 i2c oled screen not working When I try to scan the i2c address it stays stuck on "i2c Address Scanner" which is the first line of the code.
My screen is connected with VCC-5V, GND-GND, SCL- 4.7K resistor->A5, SDA- 4.7K resistor->A4.
Nothing displays on screen, and I even tried without the resistors. I also tried with some 10K resistors and same result.

Here in the picture you can see how I connected the screen to the nano. SDA-A4, SCL-A5, VCC-5V, GND-GND.

From what I am reading it is not properly connected.  You are getting what I would expect. ACL of the device goes directly to A5 and a pull up resistor to +5. Same thing with SCL, connected directly, both need pull ups. You did not state what it is connected to. If there is nothing connected you will get nothing. Also the old wire library did not support timeout so you could hang indefinitely.


delete the memory or re-upload a program At the moment I am following the instructions of this project https://github.com/JoernL/LimiTTer. Besides the peripheral parts like a Bluetooth module and an NFC module, the central unit is an Arduino Pro Mini.
I am a bloody novice with Arduino and just taught myself how to solder stuff. So far, I successfully uploaded the program from the project above to the Arduino Mini Pro and will continue as soon as the other parts arrive.

Anyhow, since I am strictly following the instructions I have some serious knowledge gaps and hope you can help me out. So, for instance.

How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?
How can I delete a program from the Arduino board?
When I upload a program, will the program that is already on the Arduino been overwritten?
Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?

In yellow is how much bytes does your program take.

In purple is how much bytes are available on your board.

In green is how many bytes does your global variables take.

In orange is how many bytes are left for local variables.

In blue is how many bytes are available for all of your variables.

In red is the general specs of your board and to which COM port it is connected to.

  How can I delete a program from the Arduino board?

Once  a new program is uploaded, the old one is deleted (somewhat). Still, you get all your bytes back and it is like if you start from scratch

  When I upload a program, will the program that is already on the Arduino been overwritten?

Yes.

  Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

An Arduino can only execute 1 program at the time. It doesn't usualy hold on to any other programs, but can store 1024 bytes in it's EEPROM. This lets your write in the EEPROM with a program and access that data with an other.


Reading from a pin Arduino Uno (assembly) I am creating a project in which an Arduino reads (gets) a value from
a DHT sensor. The DHT sensor returns two values:

Temperature
Humidity

My assembly code:

sbi ddrd,5
cbi ddrd,2
sbi portd,5

start:

in r16,Pind2
cpi r16,80
brne On

jmp start

On:
cbi portd ,5
jmp start

After the code, the light remains turned on, but if the sensor sends '80'
and I get it correctly it should be turned off.

Question: Am I Using the write way to read a pin?

You are simply reading the state of the input pin - this won't work.

Study the datasheet for the DHT22, available from Sparkfun or eslewhere.

To get data from the DTH22, you must first send a start signal, wait a specified time, then watch the level of the data line, measuring the time of each bit to determine whether it is a 1 or 0, and store the bits in five 8-bit variables.  You can then examine those variables to determine the temperature and humidity.


Where to use "static volatile bool"? Why in the piece of code below we use "static volatile bool"?

static volatile bool wifi_connected = false;

taken from here: https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino

static means that the global will only be accessible inside the current translation unit.

volatile means that while(!wifi_connected){/*...*/} cannot be optimized to if(!wifi_connected)while(true){/*...*/}

These things are orthogonal. So you would use static volatile when you need both properties.


A library for manipulate Intel Hex data? For a project i need to extract some data from an external eeprom and then store it somewhere. Suddenly after some manipulations (not necessarly with Arduino board) i need to put them in an external eeprom.

What I would do is to convert the extracted data from the EEPROM in Intel Hex data and vice versa.
To do this I wanted to know if there is already a library for that purpose "ready to use" made for Arduino boards.

thanks

Why does it have to be in Intel Hex format? You could write out the EEPROM to the serial port one byte to a line, or something. Something like this:

#include <EEPROM.h>

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

  for (int addr = 0x0000; addr < 0x0010; addr++)
    {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
    }

}  // end of setup

void loop ()
{
}  // end of loop

I'm not personally aware of a library that happens to write out/read in, Intel Hex format from/to the EEPROM.

I have code that uploads and downloads files to the Arduino. Inside that is code to read/write Intel hex format. However it isn't a library.

Inside File_Utils.ino are some comments that show the format:

/*
Line format:

  :nnaaaatt(data)ss

  Where:
  :      = a colon

  (All of below in hex format)

  nn     = length of data part
  aaaa   = address (eg. where to write data)
  tt     = transaction type
           00 = data
           01 = end of file
           02 = extended segment address (changes high-order byte of the address)
           03 = start segment address *
           04 = linear address *
           05 = start linear address *
  (data) = variable length data
  ss     = sumcheck

            * We don't use these

*/

In that file is code to write Intel Hex format (reading from Flash, not EEPROM):

void readFlashContents ()
  {
  if (!haveSDcard)
    {
    Serial.println (F("*** No SD card detected."));
    return;
    }

  progressBarCount = 0;
  pagesize = currentSignature.pageSize;
  pagemask = ~(pagesize - 1);
  oldPage = NO_PAGE;
  byte lastMSBwritten = 0;

  while (true)
    {

    Serial.println ();
    Serial.println (F("Choose file to save as: "));

    getline (name, sizeof name);
    int len = strlen (name);

    if (len < 5 || strcmp (&name [len - 4], ".HEX") != 0)
      {
      Serial.println (F("File name must end in .HEX"));
      return;
      }

    // if file doesn't exist, proceed
    if (!sd.vwd()->exists (name))
      break;

    Serial.print (F("File "));
    Serial.print (name);
    Serial.println (F(" exists. Overwrite? Type 'YES' to confirm ..."));

    if (getYesNo ())
      break;

    }  // end of checking if file exists

  // ensure back in programming mode
  if (!startProgramming ())
    return;

  SdFile myFile;

  // open the file for writing
  if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
    {
    Serial.print (F("Could not open file "));
    Serial.print (name);
    Serial.println (F(" for writing."));
    return;
    }

  byte memBuf [16];
  bool allFF;
  unsigned int i;
  char linebuf [50];
  byte sumCheck;

  Serial.println (F("Copying flash memory to SD card (disk) ..."));

  for (unsigned long address = 0; address < currentSignature.flashSize; address += sizeof memBuf)
    {

    unsigned long thisPage = address & pagemask;
    // page changed? show progress
    if (thisPage != oldPage && oldPage != NO_PAGE)
      showProgress ();
    // now this is the current page
    oldPage = thisPage;

    // don't write lines that are all 0xFF
    allFF = true;

    for (i = 0; i < sizeof memBuf; i++)
      {
      memBuf [i] = readFlash (address + i);
      if (memBuf [i] != 0xFF)
        allFF = false;
      }  // end of reading 16 bytes
    if (allFF)
      continue;

    byte MSB = address >> 16;
    if (MSB != lastMSBwritten)
      {
      sumCheck = 2 + 2 + (MSB << 4);
      sumCheck = ~sumCheck + 1;
      // hexExtendedSegmentAddressRecord (02)
      sprintf (linebuf, ":02000002%02X00%02X\r\n", MSB << 4, sumCheck);
      myFile.print (linebuf);
      lastMSBwritten = MSB;
      }  // end if different MSB

    sumCheck = 16 + lowByte (address) + highByte (address);
    sprintf (linebuf, ":10%04X00", (unsigned int) address & 0xFFFF);
    for (i = 0; i < sizeof memBuf; i++)
      {
      sprintf (&linebuf [(i * 2) + 9] , "%02X",  memBuf [i]);
      sumCheck += memBuf [i];
      }  // end of reading 16 bytes

    // 2's complement
    sumCheck = ~sumCheck + 1;
    // append sumcheck
    sprintf (&linebuf [(sizeof memBuf * 2) + 9] , "%02X\r\n",  sumCheck);

    myFile.clearWriteError ();
    myFile.print (linebuf);
    if (myFile.getWriteError ())
       {
       Serial.println ();  // finish off progress bar
       Serial.println (F("Error writing file."));
       myFile.close ();
       return;
       }   // end of an error

    }  // end of reading flash

  Serial.println ();  // finish off progress bar
  myFile.print (":00000001FF\r\n");    // end of file record
  myFile.close ();
  // ensure written to disk
  sd.vwd()->sync ();
  Serial.print (F("File "));
  Serial.print (name);
  Serial.println (F(" saved."));
  }  // end of readFlashContents

That should give you some tips about how to write out the file. Look in my code to see the reading code as well. However as I said, you don't necessarily have to use that format if you just want to manipulate the data yourself.


Read an analog signal without changing it? Or should I start over? Hi! I'm still working on my kettle project. I want to obtain the kettle temp from the existing thermometer. I'm able to do this, but much like trying to look at an electron my circuits all reduce the voltage going to the kettle control board. This means the kettle's microcontroller (SN8P2722  SONiX) acts as if the kettle is cooler than it really is.

I don't think there is an easy way to program this microcontroller (if there is I'd love to know) -- I suspect the bad temp data will lead to overheating and hot water all over my kitchen.

Is there any way to passively obtain the voltage? I've been looking into the way that voltmeters work. Is this the right idea? is there a breakout board for this?

I really wanted to have the existing buttons still work as they always have. I've done this with power. I can press it remotely or on the kettle and I can tell of the kettle is on or off both on the control panel and remotely.

I can press all the other buttons remotely but I can't tell if it's working without knowing the kettle temp.

Maybe I should try to replace the entire control board? What would be easier? I'm something of a beginner.

A JFET op amp such as the TL071 has an input impedance in the hundreds of gigaohms or higher. Using one to buffer the voltage should allow you to sample it without much interference to the existing circuit.


Error declaring two-dimensional array: 'x' was not declared in this scope I'm trying to declare a 2-D array where each letter in the alphabet is keyed to a corresponding LED in my LED strip. But when I try to declare the array, Arduino flags the values and gives me a "not declared in this scope" error. I have no idea why. Am I missing a library or is it incorrect syntax?

Some of the places I've looked say to make sure it's declared globally. I've declared the array before void setup but it still doesn't work. Here's what I've got before void setup:

#include <Adafruit_NeoPixel.h>

#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, PIN, NEO_GRB + NEO_KHZ800);

//Create a 2-D array to store each letter and
//its corresponding LED number
char charKey[26][2]={
  {a, 0},
  {b, 2},
  {c, 4},
  {d, 6},
  {e, 8},
  {f, 20},
  {g, 18},
  {h, 16},
  {i, 14},
  {j, 12},
  {k, 10},
  {l, 22},
  {m, 24},
  {n, 26},
  {o, 28},
  {p, 30},
  {q, 40},
  {r, 38},
  {s, 36},
  {t, 34},
  {u, 32},
  {v, 42},
  {w, 44},
  {x, 46},
  {y, 48},
  {z, 50}
};

Without quotes, a, b, c etc. are just names. You didn't declare any of them, so the compiler complains.
Put single quotes around the letters to let the compiler know that they are char literals.


Uploading new sketch to Leonardo-type boards when you've changed the HID mode I have Sparkfun Pro Micro (Leonardo compatible board). I got it because I plan to build my own array of controls for use in flight/racing sims.

My starting point is LeoJoy, and I didn't have any trouble getting this up and running. Installed just fine, and I have a programmable HID joystick available in windows. It seems to work by modifying the RAWHID code in the default libraries to spoof being a HID joystick. However, my board was now stuck in joystick mode, with no available COM ports for uploading new sketches.

Resetting the board (by grounding the RST pin), enables the COM port, but very, very briefly. Not enough time to send new sketches.

After about an hour of trying different timing, I finally did upload an empty sketch to the board before it went into Joystick mode. So I'm good for now, but I'm a bit worried that I'm going to have to repeat this every time I want to make a change to my program.

Am I doing something completely noobish here? Is this the correct way to program a board that has been forced to act as a joystick? Is there a better way?

Perhaps there's some code I can put into my sketch that will delay the change of USB behavior for a few seconds. That way, it will allow me to recompile and submit my sketches after a reset without having to rush the timing.

From Sparkfun's page Pro Micro Hook-upGuide

When a Pro Micro is externally reset (by pulling the RST pin low), it’ll only briefly (<750ms) start the bootloader before continuing on to the sketch. If you need the bootloader to run longer, resetting twice quickly will get the Pro Micro to enter bootloader mode for eight seconds.

Hope that helps! If not there are some other procedures you might want to look into.


How can my library source code instantiate an object from another library? I'm having trouble explaining my issue. What I'm doing is creating a library to work easily with the RFID reader/writer RC522 module. I need to create an object of the library MFRC522 in my .cpp file to be able to communticate with the module itself. I want my constructor end up like this:UltimateRFID rfid(53, 5);, the parameters being the slave select and the reset pins, respectively.
The problem is that I don't know how to make my constructor so that it is within the scope of the functions that require the MFRC522 object to be called. Below's my code.

#include "Arduino.h"
#include "UltimateRFID.h"
#include <MFRC522.h>

MFRC522::MIFARE_Key key;

UltimateRFID::UltimateRFID(int ss, int rst)
{
   MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
}

void UltimateRFID::initialize() //sample of a function that uses the MFRC522 object
{
  //digitalWrite(49, HIGH);
  digitalWrite(2, LOW);
  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }
  mfrc522.PCD_Init();
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

}

Now comes my header file, although I'm not sure it matters much.

#ifndef UltimateRFID_h
#define UltimateRFID_h

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

class UltimateRFID
{
  public:
    UltimateRFID(int ss, int rst);
    void initialize();
  private:
    MFRC522::MIFARE_Key key;
};

#endif

Please be patient, it's my first library.

Why not have your class just extend the MFRC522 class?

#include <MFRC522.h>

class UltimateRFID : public MFRC522 {
    private:
        MIFARE_Key key;

    public:
        UltimateRFID(uint8_t ss, uint8_t rst) : MFRC522(ss, rst) {}
        // your other methods
        void initialize();
};

void UltimateRFID::initialize() {
    //digitalWrite(49, HIGH);
    digitalWrite(2, LOW);
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }
    PCD_Init();
    if ( ! PICC_IsNewCardPresent()) {
        return;
    }
    if ( ! PICC_ReadCardSerial()) {
        return;
    }
}

UltimateRFID rfid(53, 5);

void setup() {
    rfid.initialize();
}

void loop() {}

Your class then becomes a "flavour" of MFRC522 with additional functionality. It can access all the public functions of the MFRC522 class, since they are now a part of your class.

Anything you can do with an MFRC522 object you can now do with your object. As well as your extra functions.


Project wont compile when I place functions below function calls I use VSCode, not the Arduino IDE. I saw and tried to use a lot of code snippets which are provided for Arduino projects...

So when I copy/paste these examples into my VSCode and try to compile it fails. (I won't believe that people offer non-working examples.)

When I place the functions above the function calls it compiles.

Is this normal behavior or do I have to add some settings to get this working as provided?

Fails in VSCode (works in Arduino IDE):

#include "Arduino.h"
void setup() {
}
int zero = 0;

void loop() {
  zero = myfunction();
}

int myfunction(){
  return 0;
}

Works in VSCode (Works in Arduino IDE):

#include "Arduino.h"

void setup() {
}
int zero = 0;

int myfunction(){
  return 0;
}

void loop() {
  zero = myfunction();
}

You need to declare your function before you use it.  So either the whole function body needs to be before the usage, or you must add a function prototype declaration.

void myfunction();

myfunction();

void myfunction(){
  return 0;
}


Solid-state relay boards: Can they be used to switch audio signals? So I tried to use one of those widely available solid-state relay boards to switch some 12V power, and I found out the hard way that they are not designed to switch DC current. They use some sort of variac that only works when AC voltage is applied. Do I have that right??

So I got this other project where I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this. If I send audio through these relays, is it going to work as planned? Will I suffer any noticeable delay, signal degradation or attenuation?

A solid-state relay seems to be the totally wrong tool for the job. The image you posted shows it is intended to switch 240V AC. So it is designed to switch something like a 240V light on and off.

Relays in general are things designed to connect one thing to another (eg. power to a light). They just aren't designed to switch audio signals.

  I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this

The expression "when the only tool you have is a hammer, everything looks like a nail" springs to mind.

There are chips designed to multiplex analog signals (as I describe on this page). That would be closer to what you need.

However that chip (the 74HC4067) is a "choose one input from many" sort of design. It isn't going to let you fade one audio signal in or out (neither would the relay for that matter).


Arduino Pro Mini lower BOD problem I am planing to build a project where an arduino pro mini 3.3V runs on 2 aa batteries. The standard brown out detection shuts it down at about 2.7/2.8V where it could run on lower voltages too.
So I changed the efuse to get the BOD down to 1.8V. I connected a serial to usb converter and used avrdude:

avrdude -c avrisp -p m328p -P COM5 -b 19200 -U lfuse:w:0xff:m -U hfuse:w:0xda:m -U efuse:w:0x06:m

Then I tried to upload a program using the arduino 1.0.3 IDE but I got this error:

avrdude: stk500_getsync(): not in sync: resp=0x1c

With 1.6.4 I got another error:

    avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x75
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1c

After some googling I tried some lower baud rate (the standard seems to be 57600). With 19200 everything worked with avrdude, so I created a new entry in the boards.txt

    ##############################################################

pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328 BOD 1.8V

pro328.upload.protocol=arduino
pro328.upload.maximum_size=30720
pro328.upload.speed=19200

pro328.bootloader.low_fuses=0xFF
pro328.bootloader.high_fuses=0xDA
pro328.bootloader.extended_fuses=0x06
pro328.bootloader.path=atmega
pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
pro328.bootloader.unlock_bits=0x3F
pro328.bootloader.lock_bits=0x0F

pro328.build.mcu=atmega328p
pro328.build.f_cpu=8000000L
pro328.build.core=arduino
pro328.build.variant=standard

And burned a bootloader using the 1.0.3 IDE again. After that I could upload a blink program. My goal is to upload a mysensors sketch though and that doesn't work. I am getting an error

avrdude: verification error, first mismatch at byte 0x0002
         0x69 != 0x61
avrdude: verification error; content mismatch

Mysensors seems to have general problems with old arduino IDEs so I tried to use the newer 1.6.4 but I can't define my own board there and if I try it without I get hte out of sync error (because it's still using the wrong baudrate I guess).

I also tried using another arduino uno as ISP => same results

How can I fix this? Is there a way to define my own board for 1.6.x?
Whats the standard way of doing this and why does the change of the efuse results in me not beeing able to program the mini any longer?

Thanks for every answer/help!

When you go below (or above) the manufacturer's voltage/clock specifications, expect some problems. One chip may work another will not.  Remember the lower the voltage normally the slower the clock needs to be.  The CPUs are cut from a wafer (size and geometry specific) which may contain many thousand CPU die, they are at different locations on the wafer they will be a little different and they make more then one wafer.

Check the data sheet, it will show what clock speed will work at what voltage.  As the CPU clock changes so will your baud rate so plan on recalculating that if you change the clock. Example:  If you are operating with a 16MHz clock and change it to 8MHz the baud will be exactly 1/2.  If at 9600 it will be 4800 unless you modify the clock dividers.

Your error indicates a potential baud rate problem. One of the funny things that happens when the voltage is above/below the manufacturer's speck not all instructions operate properly over temperature. Clock problems should be expected.


PT100 and MAX31865 readings showing wrong I am using PT100 (3 Wire) to measure the temperature with Arduino Uno and MAX31865.
I have connected everything perfectly.
Configuration in the code i am using is :

max1.begin(MAX31865_3WIRE);

And the output is:

output

RTD value: 0
Ratio = 0.00000000
Resistance = 0.00000000
Temperature = -242.02

I am testing it in a room temperature.

My question is , is there any settings or calibration that i need to do, or any other way to test the PT100 sensor, because the temperature is showing correct readings ?

I nearly have the same problem. I use five of the MAX31865-Boards with 2-Wire Termocouples on an Arduino Nano. Two of the five boards are working perfectly. The other 3 boards show exactly the same wrong behaviour you described. My temperature readings are exactly like yours (-242.02).

But I think I found the reason for the not working ones: The two working boards I bought on Amazon. The other three not working boards I bought on AliExpress. Maybe I (and maybe you too) got really bad fakes from China and they are simply dead :(

(BTW: If I remove one working board from the SPI bus and read out the temperature with the arduino, I get also the value of -242.02. This value seems to be an error value in the Adafruit MAX31865 library)

EDIT: Fixed it with a workaround!Like shown in the picture below, simply remove the wrong component (SMD Capacitor) and create a solder bridge . See comments for more informations!

Here is a picture of my modification of one chinese board as requested by the comments:

(It's not the best solution, but it works. For final using you should get the right filter ferrite and solder it on the board!)


7-segment display code What is the meaning of BitSet = bitRead(numeral[number], segment);?

const byte numeral[10] = {
  //ABCDEFG /dp
  B11111100,  // 0
  B01100000,  // 1
  B11011010,  // 2
  B11110010,  // 3
  B01100110,  // 4
  B10110110,  // 5
  B00111110,  // 6
  B11100000,  // 7
  B11111110,  // 8
  B11100110,  // 9
};

// pins for decimal point and each segment
//                          dp,G,F,E,D,C,B,A
const int segmentPins[8] = { 5,9,8,7,6,4,3,2};

void setup()
{
  for(int i=0; i < 8; i++)
  {
    pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output
  }
}

void loop()
{
  for(int i=0; i <= 10; i++)
  {
    showDigit(i);
    delay(1000);
  }
  // the last value if i is 10 and this will turn the display off
  delay(2000);  // pause two seconds with the display off
}

// Displays a number from 0 through 9 on a 7-segment display
// any value not within the range of 0-9 turns the display off
void showDigit( int number)
{
  boolean isBitSet;

  for(int segment = 1; segment < 8; segment++)
  {
    if( number < 0 || number > 9){
      isBitSet = 0;   // turn off all segments
    }
    else{
      // isBitSet will be true if given bit is 1
      isBitSet = bitRead(numeral[number], segment);
    }
    isBitSet = ! isBitSet; // remove this line if common cathode display
    digitalWrite( segmentPins[segment], isBitSet);
  }
}

bitRead(x, y) takes a value x, and looks at bit number y.

So, if:

y is the number 2;
x is 53 (binary number 0 0 1 1 0 1 0 1)

                                       ^

it looks at bit #2. Bits are counted from the right starting at 0 - I have indicated the bit in question above.

So, bitRead(53, 2) would return 1, since bit #2 in 53 is a 1.

In the above program, the clever programmer has coded whether to light or not light the LED for each segment of the display in a single byte for each possible number to display. The digit 8 has all seven of its LEDs lit up, so you'd expect the encoding for 8 to have lots of binary 1s in it - and sure enough, it does (B11111110)! And the digit 7 has only three segments lit up, so you'd expect only 3 bits to be set. Sure enough, B11100000.

The comment at the top describes what each of the bits represent - the last bit is the decimal point, which is never set...


ESP8266 Serial Communication with ATMega328P I am isolating the ATMega328P from the Arduino Uno. I have used it for many other projects, so it does work as intended. Also, I have used my ESP8266-01 for other projects and works great (including serial communication).

I am trying to get the ESP8266-01 to make the ATMega328P pin 13 blink an LED. That is all.

When the ESP8266 is hooked to the TX/RX of the arduino board, the program works exactly as intended. I hook it up the exact same way to the ATMega328P and it doesn't work.

I am using baud rate of 9600 for the communication and using a 16MHz crystal for the ATMega328P.

simulate this circuit – Schematic created using CircuitLab

The controller is getting 3.3v from the supply as well. And pin 13 is supposed to turn on/off depending on the serial value. Below is the code for the ESP8266:

#include <ESP8266WiFi.h>

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

void loop() {
  delay(10000);
  Serial.write("LED ON");
  delay(10000);
  Serial.write("LED OFF");
}

And below is the code for the ATMega328P:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600);
  pinMode(13, OUTPUT);
}

void loop()
{
  if(esp8266.available())
  {
    String command = "";
    while(esp8266.available())
    {
      command += (char)esp8266.read();
    }

    if(command == "LED ON") {
      digitalWrite(13, HIGH);
    }

    if(command == "LED OFF") {
      digitalWrite(13, LOW);
    }
  }

  delay(500);
}

As stated, they work great separately, but when I try serial communication with them together, it doesn't work.

P.S. I usually set my ESP8266 baud rate to 115200, but the ATMega328P, I believe, needs to run at 9600 because of the 16MHz clock frequency. Not sure about this part, though.

EDIT:

simulate this circuit

Generally, try to debug the problem.  Evidently either you're not getting data from your esp8266.available() and/or esp8266.read(), or it's not the right data.  Put traces (Serial.println(...)) in, print things out, and find out what's going wrong.

Specifically, I suspect the issue here is that you are relying on all the data being available immediately: you check esp8266.available() which will tell you whether one or more bytes is available.  Then you esp8266.read() until there are no more bytes available.  What if there's a 1ms delay between bytes arriving?  You'll get,perhaps LED O, esp8266.available() will tell you there's no more data (there's not, yet!) and you stop reading.

You could probably get it working by putting a small delay() in:

while(esp8266.available())
{
  command += (char)esp8266.read();
  delay(100);
}

That's a solution (probably) but not a good one.  A better solution would be to make your commands LED_ON\n and LED_OFF\n - and read until you get a \n.


RGB Led - mixing colors using analogWrite Currently I'm controlling an RGB LED with my Arduino Nano.

I'm mixing the colors using analogWrite

Though, the LED's don't light up at all for low analogwrite values and the difference between the levels is not visible (to me).

I'm using 100 Ohms resistors between the LED's, using a 680Ohms didn't seem to make a difference.

Analogwrite is working by toggling the LED's fast (PWM)? So not by lowering voltage? This is why I think it's weird that they don't light up at all, on low write values.

My sketch below:

#include <SoftwareSerial.h>

int r, g, b = 0;
String command = "";
const byte rxPin = 11;
const byte txPin = 10;

SoftwareSerial blueTooth (rxPin, txPin);

void handleCommand() {
  r = rgbFromCommand("r=",";");
  g = rgbFromCommand("g=",";");
  b = rgbFromCommand("b=",";");

  if(r != -1){
    analogWrite(A2,r);
  }
  if(g != -1){
    analogWrite(A1,g);
  }
  if(b != -1){
    analogWrite(A0,b);
  }
}

int rgbFromCommand(String prefix, String postfix) {
  int idx = command.indexOf(prefix);
  int endIdx = command.indexOf(postfix,idx);
  if(idx>=0 && endIdx>=0){
    idx+=2;
    return command.substring(idx,endIdx).toInt();
  }
  return -1;
}

void setup() {
  pinMode(rxPin,INPUT);
  pinMode(txPin,OUTPUT);
  Serial.begin(9600);
  blueTooth.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    // read the incoming byte:
    char incomingByte = Serial.read();

    if(incomingByte == '\n'){
      handleCommand();
      command = "";
    }else{
      command += incomingByte;
    }
  }
  if(blueTooth.available() > 0){
        // read the incoming byte:
    char incomingByte = blueTooth.read();

    if(incomingByte == '\n'){
      handleCommand();
      command = "";
    }else{
      command += incomingByte;
    }
  }
}

Analog pins aren't PWM pins. Instead you have to use the pins marked with a ~

Pins that aren't PWM pins will be off with a value of 0-127 and on with a value between 128 and 255.


decomposition long number to byte and recomposition With FRAM I'm using Adafruit FRAM for my little project and have some trouble with recomposition of LONG Variable , right now the recomposition on INTEGER it's fine.
Where I'm wrong with recomposition of LONG number? Thank's for reply :D

#include <SPI.h>
#include "Adafruit_FRAM_SPI.h"

/* Example code for the Adafruit SPI FRAM breakout */
uint8_t FRAM_CS = 10;

//Adafruit_FRAM_SPI fram = Adafruit_FRAM_SPI(FRAM_CS);  // use hardware SPI

uint8_t FRAM_SCK = 13;
uint8_t FRAM_MISO = 12;
uint8_t FRAM_MOSI = 11;
//Or use software SPI, any pins!
Adafruit_FRAM_SPI fram = Adafruit_FRAM_SPI(FRAM_SCK, FRAM_MISO, FRAM_MOSI, FRAM_CS);

uint16_t          addr = 0;

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif

void setup(void) {
#ifndef ESP8266
  while (!Serial);     // will pause Zero, Leonardo, etc until serial console opens
#endif

  Serial.begin(9600);

  if (fram.begin()) {
    Serial.println("Found SPI FRAM");
  } else {
    Serial.println("No SPI FRAM found ... check your connections\r\n");
    while (1);
  }
  int interoDaScrivere = 12345;
  long longDaScrivere = 123456789;
  byte a1 = 0;
  byte a2 = 0;
  byte intPt0 = 0;
  byte intPt1 = 0;
  byte longPt1 = 0;
  byte longPt2 = 0;
  byte longPt3 = 0;
  byte longPt4 = 0;
  a1 = byte(interoDaScrivere);        // si scompone l'intero in 2 byte
  a2 = byte( interoDaScrivere >> 8);
  //decomposition Long

  byte b1 = (longDaScrivere);
  byte b2 = (longDaScrivere >> 8);
  byte b3 = (longDaScrivere >> 16);
  byte b4 = (longDaScrivere >> 24);

  //--------------

  // Read the first byte
  uint8_t test = fram.read8(0x0);
  Serial.print("Restarted "); Serial.print(test); Serial.println(" times");

  // Test write ++
  fram.writeEnable(true);
  fram.write8(0x0, test + 1);
  fram.writeEnable(false);
  /*
    fram.writeEnable(true);
    fram.write(0x1, (uint8_t *)"FTW!", 5);
    fram.writeEnable(false);
  */

  fram.writeEnable(true);
  fram.write8(1, a1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(2, a2);
  fram.writeEnable(false);

  fram.writeEnable(true);
  fram.write8(3, b1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(4, b2);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(5, b3);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(6, b4);
  fram.writeEnable(false);

  //ricomposizione INT
  int interoRicomposto = 0;
  intPt0 = fram.read8(1);
  intPt1 = fram.read8(2);
  //INT RECOMPOSITION
  interoRicomposto =  ((intPt1 << 8) | intPt0);
  // ricomposizione LONG
  long longRicomposto = 0;
  longPt1 = fram.read8(3);
  longPt2 = fram.read8(4);
  longPt3 = fram.read8(5);
  longPt4 = fram.read8(6);
 //LONG RECOMPOSITION
  longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

  Serial.print("A1 F0 ");
  Serial.print(a1);
  Serial.print(" ");
  Serial.println(intPt0);
  Serial.print("A2  F1 ");
  Serial.print(a2);
  Serial.print(" ");
  Serial.println(intPt1);
  Serial.println(interoRicomposto);

  Serial.print("b1 LongPt1 ");
  Serial.print(b1);
  Serial.print(" ");
  Serial.println(longPt1);
  Serial.print("b2 LongPt2 ");
  Serial.print(b2);
  Serial.print(" ");
  Serial.println(longPt2);
  Serial.print("b3 LongPt3 ");
  Serial.print(b3);
  Serial.print(" ");
  Serial.println(longPt3);;
  Serial.print("b4 LongPt4 ");
  Serial.print(b4);
  Serial.print(" ");
  Serial.println(longPt4);

  Serial.println(longRicomposto);

}

void loop(void) {

}

There is one very obvious error in your code: You are writing the long
number LSB (least significant byte) first: the LSB goes at address 3 of
the FRAM, while the MSB (most significant byte) goes at address 6. You
reconstruct the number with

longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

which puts longPt1 (contents of address 3) as the most significant
byte. Thus you are swapping all the bytes around.

Then there is a more subtle error. longPt1 is a byte. According to the
C++ promotion rules, it is implicitly promoted to int before any
arithmetic or logical operation. But since an int is 16-bits, you are
shifting all the bits out when you do longPt1 << 24. You should cast
the numbers to a 32-bit type before shifting, as follows:

long longRicomposto = (uint32_t) longPt1 <<  0
                    | (uint32_t) longPt2 <<  8
                    | (uint32_t) longPt3 << 16
                    | (uint32_t) longPt4 << 24;

Note that I am casting to an unsigned type. Shifting a 1 into the bit
sign of an integer is undefined behavior in C++: the shift must be done
with an unsigned type, then, if needed, cast to a signed type.


How to make an electronic suction cup? The uArm is a robot arm with a suction cup (or gripper). I'd like to try to make just the suction part of it, and I'm wondering what components I'd need?

By the looks of it, I'd need a hobby vacuum pump, but these seem few and far between on UK components sites.

How would I power it? It looks like they're all 12v, and I believe Arduino gives you 5v?

Exact what components would I need? Do I need any shields?

Here's a short video of the suction cup I'd like to copy:

Just a note for those who wonder the same and are in need of a vacuum: In theory, you can use Venturi effect (or Bernoulli's Principle; it's basically the same) to create a vacuum. Or go buy an Aspirator pump. Since English is not my native language it's difficult for me to explain it in my own terms, but I'll try to give you a rough idea anyway. (Google it or feel free to answer with a better explanation).

First you need some flow of a fluid or gas (air from a compressor or water from a household outlet are fine). You pass that flow through left-to-right in a T-pipe (I'll call that the "flow pipe"). This will result in a weak vacuum in the orthogonal pipe (I'll call this the "vacuum pipe"), which you can connect to your suction cup.

The strength of the vacuum depends on the pressure in the "flow pipe". That means a higher velocity of your matter in the "flow pipe" is good (either a stronger compressor or smaller diameter of your flow pipe).

If I understand my physics book correctly, a higher density of the matter in your flow pipe will also produce a stronger vacuum. If you need a really strong vacuum, you could even use a water compressor, i.e. high pressure cleaner; but I suppose even a small air compressor will outperform a household water outlet (and you could toggle it from an Arduino with a relay board).

Since the air in the vacuum pipe expands more than many other materials, you could try to replace it with i.e. oil (be aware you'll pull out some of the air/replacement material at the intersection in aspirator!). This optimization is dangerous with a normal vacuum pump, since these usually break when sucking up fluids into their internals.

Also using an aspirator has the upside of not needing to buy a vacuum pump if you already own a compressor. On the other hand, that setup might be even louder (and possibly less efficient) than a dedicated vacuum pump.


Arduino nano select port option is blurred | Driver issue I have just bought arduino nano board. when i connect the board via usb, system detects the new device but i am not able to select port in arduino ide for writing any code on board. I checked my device manager it says

The drivers for this device are not installed. (Code 28)
There are no compatible drivers for this device.

I have also updated my board and library list in arduino ide.
please help me out?

on my nano board CH340G USB<-->uart chip was present, so i installed driver for that chip and everything works fine now. :P

link for the driver (windows 8,10): http://www.arduined.eu/ch340-windows-8-driver-download/


Arduino uno and 1602A I2C not working I'm a newbie in engineering.

I bought this with arduino learning kit.

It's simply not working.

There are several possible problems:

The display is not working due to a hardware problem. It could need to be repaired or soldered better.
The library that I chose could be buggy (software problem)

How can I check this? Thanks!

PS Build-in led is blinking as expected.

Here is the code:

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

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup()
{
  lcd.init();
  lcd.begin(8,2);

  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("TEST");
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  lcd.setCursor(0, 0);
  lcd.print("   ");
  delay(1000);
}

Try with this address 0x3F or 0x27

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // or 0x27
void setup() {
lcd.begin(16, 2);
}
void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("TEST");
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  lcd.setCursor(0, 0);
  lcd.print("   ");
  delay(1000);
}


Char Array Buffers String UINT8 So, I have an ATTiny85 sending data, awesome.
I would like to have it send a message that consists of a few concatenated parts.

I have been reading about strings, buffers, chars, toCharArray and more for about 6 hours now and am completely puzzled by this.

Below, the variable deze will no transmit, but msg will.
So I tried to do something like char *deze = "hello" + "world"; but that also fails.

What would be the best way to construct a piece of data that will be send by my 433MHz transmitter. I need to combine INT, String and float before sending it as uint8_t (bytes?).

#include <RH_ASK.h>

#define R_PIN PB4
#define T_PIN PB1
#define L_PIN PB3

RH_ASK driver(2000, R_PIN, T_PIN);

void setup()
{
  if (!driver.init()){
    pinMode(L_PIN, OUTPUT);
    digitalWrite(L_PIN, HIGH);
    delay(500);
    digitalWrite(L_PIN, LOW);
    delay(500);
  }
}

void loop()
{
  char deze[5];
  char *msg = "gewonechar";

  String thijs = "thijs";
  thijs.toCharArray(deze, sizeof(deze)-1);

  driver.send((uint8_t *)deze, strlen(msg));
  driver.waitPacketSent();
  delay(200);
}

[edit]
This is the working code on the receiver side.

struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    if (driver.recv(buf, &buflen)) {

      memcpy(&myData, buf, buflen);

      Serial.print("ID: ");
      Serial.println(myData.id);

      Serial.print("Pin: ");
      Serial.println(myData.pin);

      Serial.print("Value1: ");
      Serial.println(myData.value1);

      Serial.print("Value2: ");
      Serial.println(myData.value2);

      Serial.println("");
    }
    server.handleClient();
    yield;
}

And the transmitter

#include <RH_ASK.h>

#define BAUD 2000
#define RX 11
#define TX 12

RH_ASK driver(BAUD, RX, TX);

struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

void setup() {
    Serial.begin(9600);   // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{
    struct data myData;

    myData.id = 1001;
    myData.pin = 4;
    myData.value1 = analogRead(4);
    myData.value2 = analogRead(5);

    driver.send((uint8_t *)&myData, sizeof(myData));
    driver.waitPacketSent();
    delay(2000);
}

Library used: http://www.airspayce.com/mikem/arduino/RadioHead/

First off you never want to use String - especially on a chip with a mere 512 bytes of SRAM.

You should really be learning about struct for sending of data in the most efficient way.  A struct is a complex data type that combines multiple bits of data into one single variable - a bit like a record in a database.

You should avoid sending text as it is generally wasteful. The odd character, yes, but not whole strings of text.

For instance, you might want to send temperature, humidity and pressure:

struct data {
    int8_t temperature;
    uint8_t humidity;
    uint16_t pressure;
};

void sendData() {
    struct data myPacket;

    myPacket.temperature = 23;
    myPacket.humidity = 72;
    myPacket.pressure = 1016;

    driver.send((uint8_t *)&myPacket, sizeof(myPacket));
    driver.waitPacketSent();
}

With a struct, if you want to send text, you need to allocate enough space in the struct for your text. For instance, enough room for 9 characters plus NULL:

struct data {
    int8_t temperature;
    uint8_t humidity;
    uint16_t pressure;
    char weather[10];
};

Then, to get data into it, you (for example):

strcpy_P(myData.weather, (PGM_P)F("fog"));


Powering Arduino from 7805 voltage regulator I am trying to build an Arduino Uno based robot. My questions are the following:

1) The motor driver also has an on-board 78M05 voltage regulator from ST electronics. I used a 9V battery to power the robot, and the 9V was connected to the input of the voltage regulator, and the +5V output I used to power the Arduino. I did so by connecting the 5V from the regulator to the 5V pin on the Arduino and the GND's together. I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

2) I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

Nothing wrong with that as long as it is regulated 5V (which yours is). You can use either the 5V pin on the header, or the 5V pin on the ICSP connector. They are both the same.  It is good practice to connect a diode between 5V and VIN to prevent current flowing backwards through the onboard regulator should something connected to VIN want to draw current.

  I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

A regulator has a "drop-out" voltage. That is often in the order of 1.2V for these kind of regulators (it's certainly right for the Arduino's on-board one.

You are providing less than the regulation voltage plus the drop-out voltage, so the output of the regulator will be the input voltage minus the drop-out voltage.

As long as that is above the lowest voltage the Arduino can run from at 16MHz then it will still work fine. You should be fine down to about 4V output from the regulator, and even lower if you're lucky (you may start getting stability problems though since the ATMega328P isn't rated to run at 16MHz at lower voltages).

It also means that the GPIOs on the Arduino will be running at a lower voltage as well.


Atmega2560 USART UDR r/w conflict possible? I'm having a really weird issue with my project right now. I have an Atmega2560 using hardware serial, and the software on the other side is doing full duplex read/write at 500kbps. If I change it to be single duplex, everything works fine. But the second I try to run everything truly full duplex, I start to have some data transfer over from the transmit stream to receive stream on the device (characters that its trying to write, that it somehow ends up reading again).

I've simplified things as much as possible- disabling buffering on the arduino side, using mutexes on the client software side (to prevent overlapping read/write commands, despite the fact the underlying driver will do whatever it wants).

So, there's obviously a few potential problems here, but it has to boil down to:

a) Client software/drivers misbehaving

b) Hardware serial implementation misbehaving on the device.

I really want to rule out B, and from all my digging around, it really comes down to one question:

Is there any possible way that data written to the UDR register could somehow be read out again? I understand this register is actually 2 different registers, and just splits out reads and writes. But is there any possible way at all this data could be read again? Like, is it possible to even write to UDR and read that byte ever again? I'd really like to rule that out before I start unnecessarily tracing ISRs and all that garbage.

Here's what I've boiled the hardware serial code down to. Interrupt driven on read and direct write on write:

void MarlinSerial::write(uint8_t c) {
  while (!TEST(M_UCSRxA, M_UDREx));

  M_UDRx = c;
}

ISR(M_USARTx_RX_vect) {
  const unsigned char c = M_UDRx;
  store_char(c);
}

UPDATE: I'm an idiot. Found a buffer overrun way downstream in the device code. It just so happened that the temp response buffer for one routine butted up against the receive buffer, so it delightfully just over-ran into there. I'm happily chugging away now with 2 totally async command streams, total about 400kbps.

Is there any possible way that data written to the UDR register could somehow be read out again?

No, there is no possibility. The datasheet says:

  The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address
  referred to as USART Data Register or UDRn. The Transmit Data Buffer Register (TXB) will be the destination for
  data written to the UDRn Register location. Reading the UDRn Register location will return the contents of the
  Receive Data Buffer Register (RXB).

Further on it says:

  The transmit buffer can only be written when the UDREn Flag in the UCSRnA Register is set. Data written to UDRn
  when the UDREn Flag is not set, will be ignored by the USART Transmitter. When data is written to the transmit
  buffer, and the Transmitter is enabled, the Transmitter will load the data into the Transmit Shift Register when the
  Shift Register is empty. Then the data will be serially transmitted on the TxDn pin.

And for reception it says:

  The receive buffer consists of a two level FIFO. The FIFO will change its state whenever the receive buffer is
  accessed. Due to this behavior of the receive buffer, do not use Read-Modify-Write instructions (SBI and CBI) on
  this location. Be careful when using bit test instructions (SBIC and SBIS), since these also will change the state of
  the FIFO.

So the only thing it is possible to read is data that has been received via the RX pin (and then once and once only). All written data (assuming there is room in the TX buffer) is sent out of the TX pin.

If you are getting TX data appearing in the RX buffer then somewhere there must be some kind of connection between the TX and RX pins - either in software at the remote end (the remote device echoing everything it receives, which is perfectly possible depending on what the remote device is), or though a fault in the cabling or circuit design.


Finding ESP8266 in a network I am connecting an ESP8266 to my home network (WiFi). After successful connection, an IP is assigned to it. I am sending commands to the ESP8266 from an Android app.

What can I do to find the ESP8266 on any network where my Android app is also connected? I ask this because whenever I change the network, a new IP is assigned to the ESP8266 and I have to manually change the IP in the Android app.

I just need to find the ESP8266 on the network, get its IP address and send commands to it.

Thanks in advance.

Some solutions that have worked for me:

Reserved IP - use the router's DHCP reservation to give the same ESP the same IP each time.
Static IP - Set the ESP to use the same IP each time, bypassing the DHCP feature altogether. This also boots the ESP slightly faster. WiFi.config(ip, gateway, subnet);
Dump the IP address to Serial on boot, so that you can at least see what's assigned: Serial.println(WiFi.localIP());
Give the STA a unique name that you can find in the router's DCHP clients page: WiFi.hostname("look_here");
use mDNS to assign a domain-like local URL to the device: MDNS.begin("esp8266");// default to "http://esp8266.local/"


Which Timer can I use on the Arduino/Genuino Micro? I'm trying to implement charlieplexing with bit angle modulation on my Arduino Micro, and for that I need to use the internal timers.

Which timers of the Atmega32u4 are unused by the standard firmware? Ideally I'd like to use either Timer1 or Timer3 as they have the highest resolution.

Only Timer0 is used for millis and micros, just as with the Arduino Uno and Mega 2560.

Timer0 is used in "wiring.c".
That same file is used for the Uno, Mega 2560, Leonardo and Micro. The differences for the Leonardo is the pin numbers in "pins_arduino.h".

If you don't use PWM output with analogWrite, then you can use all of the other timers. The timers are set to certain values in the function init (also in wiring.c). But you can ignore that if you never use analogWrite.