Problematic Microcontroller and VCO - microcontroller

I hope your day is going well. I am programming a LPC1768 to send signals to at AD5791 in order to output a given frequency dependent on the output voltage of the AD5791. I have attached the circuit diagram. I have been able to seemingly read and write to the AD5791 from the LPC1768. However, when I connect the VCO to a signal analyzer I see no variation in the peak frequency when I "change" the voltage output of the AD5791. I have been programming using mbed. Below is the code I am currently using. Inputs would be greatly appreciated. I believe the issue may lie in how spi.write is implemented. The AD5791 requires 20-bit words and the LPC1768 can only send 16-bit words max. Also, there is the matter of endianness - but I believe I have solved that as I am reading out what I write to the AD5791 in the order expected.
#include "mbed.h"
SPI spi(p5, p6, p7); // mosi, miso, sclk
DigitalOut cs(p8);
int main()
{
spi.format(8,1);
spi.frequency(1000000);
cs=1;
while(1)
{
cs = 0;
spi.write(0x10);
spi.write(0xFF);
spi.write(0xFF);
cs = 1;
cs = 0;
int first = spi.write(0x90);
int second = spi.write(0x00);
int third = spi.write(0x00);
cs = 1;
printf("first register = 0x%X\n", first);
printf("second register = 0x%X\n", second);
printf("third register = 0x%X\n", third);
}
}`

Related

Code upload results in 'USB device has malfunctioned' Windows error

I am having the same problem as described in this post on the Arduino forums. I have a slight deviation in that I am using an Arduino Leonardo, but otherwise the core problem is the same.
Trying to upload a sketch to my board results in Windows stating my 'USB device has malfunctioned and Windows does not recognize it'. The COM port used for the board then disappears, as with the post above.
I tried the solution posted by Louis Davis in the linked post, which allowed me to successfully reset the board and upload a known good sketch. When this is completed, the board is able to be recognised by Windows again, and the COM port reappears; the board can be used without issue.
I have two Leonardos and I have confirmed by replicating steps across both that it is my specific code which is causing the Windows error to appear, not down to a hardware issue.
Could anyone offer pointers on what in the below code is causing this? (Code is fully commented to describe purpose/methods used)
//Code including basic setup/loop and a function I created, asking for readings to be taken from 3 sensors
//when called, and to then assign the results to global variables
//The loop function should then print the global variables in question and wait for a while before repeating
//the process
#include <Wire.h> //using an I2C breakout (accelerometer)
#include "SparkFun_MMA8452Q.h" //accelerometer breakout's library
MMA8452Q accel; //create an instance of this accelerometer
int FSR_pin = A1; //force resistor pin
const int PHOTO_pin = A0; //phototransistor pin
//declare variables to use to take a base reading, to later measure against for changes
int base_PHOTO = 0;
int base_FSR = 0;
byte base_ORIEN = 0; //using the method recommended in the accelerometer's startup page to get orientation
//readings, which they say is passed back as a byte; section 'Reading Portrait/Landscape'
//on this page https://learn.sparkfun.com/tutorials/mma8452q-accelerometer-breakout-hookup-guide
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Wire.begin();
}
void baseReading() {
base_FSR = analogRead(FSR_pin);
base_PHOTO = analogRead(PHOTO_pin);
base_ORIEN = accel.readPL();
}
void loop() {
// put your main code here, to run repeatedly:
baseReading(); //call my own function to get base readings
Serial.println(base_FSR);
Serial.println(base_PHOTO);
Serial.println(base_ORIEN);
delay(5000);
}
int takeReading() {
}
I have taken readings from each sensor individually using test sketches from the component manufacturers; the problem only appeared when I tried to combine them into one bit of code. Here's a hyperlink to the accelerometer breakout guide referenced in the above code.
Solved: The code was missing the line accel.init(); from the setup function.
I first ruled out the FSR & phototransistor I was using, as running code for only these components performed as expected. That left the MMA8452Q's code to look at.
I'd been using the manufacturer's guide as linked above for the accelerometer, and Example #3 (orientation reading) from its library to write my code out; I managed to drop the init and assumed the problem was with the new .readPL method I had put in.
The example code uses .begin instead of .init, and also uses this as part of a print statement, so I didn't immediately catch on that the purpose of its inclusion was the same.
The fixed code is as follows:
//Code including basic setup/loop and a function I created, asking for readings to be taken from 3 sensors when called and assigned to global variables
//The loop function should then print the global variables in question and wait for a while before repeating the process
#include <Wire.h>
#include "SparkFun_MMA8452Q.h"
MMA8452Q accel;
int FSR_pin = A1;
const int PHOTO_pin = A0;
//variables to use to take a base reading, to later measure against for changes
int base_PHOTO = 0;
int base_FSR = 0;
byte base_ORIEN = 0;
void setup() {
Serial.begin(9600);
Wire.begin();
accel.init(); //The new line, which allows this to run as intended
}
void baseReading() {
base_FSR = analogRead(FSR_pin);
base_PHOTO = analogRead(PHOTO_pin);
base_ORIEN = accel.readPL();
}
void loop() {
baseReading();
Serial.println(base_FSR);
Serial.println(base_PHOTO);
Serial.println(base_ORIEN);
delay(5000);
}

Type casting operation

I am using NodeMCU & Energy meter. Energy meter is Modbus RTU device which display parameter in 32 bit. With below piece of code I could able to read the data from slave but need method to type cast from into 32 bit floating & display
When I change the value to unsigned decimal in ModScan software the values showing properly. But I need to display value in 32 bit floating point.
#include <ModbusMaster232.h>
#include <SoftwareSerial.h>
float data[100];
ModbusMaster232 node(1);
// Define one address for reading
#define address 1
// Define the number of bits to read
#define bitQty 70
void setup()
{
Serial.begin(9600);
// Initialize Modbus communication baud rate
node.begin(9600);
}
void loop()
{
int result = node.readHoldingRegisters(address, bitQty);
data[0] = (float)node.getResponseBuffer(0);
data[1] = (float)node.getResponseBuffer(1);
data[2] = (float)node.getResponseBuffer(2);
data[3] = (float)node.getResponseBuffer(3);
data[4] = (float)node.getResponseBuffer(4);
data[5] = (float)node.getResponseBuffer(5);
for (int i = 0; i < 100; i++)
{
//data[i] = node.getResponseBuffer(i);
Serial.println(data[i]);
}
Serial.println("............");
}
I would like to display the reading as shown in Modbus with type casting.
Actual Modbus device output from salve:
Arduino output while read data from energy meter:
You are casting a 16-bit word into a float. Check the slave documentation to find how they map a 32-bit floating point into two Modbus registers. Basically you need to know where the least significant word is (first or second register), load them into memory (shift if necessary) and cast to float.
I am looking and trying to solve exact same problem (with same results). This may help:
function read() {
client.readHoldingRegisters(0000, 12)
.then(function(d) {
var floatA = d.buffer.readFloatBE(0);
console.log("Total kWh: ", floatA); })
.catch(function(e) {
console.log(e.message); })
.then(close);
}
This is NodeJS and javascript version, which works and Arduino does not. Complete example can be found here and it works on Raspberry Pi https://github.com/yaacov/node-modbus-serial/blob/master/examples/buffer.js

Need help displaying serial monitor on LCD

I'm having issues displaying the serial monitor on an lcd. I am not getting any error and the LCD is lit up so I don't think I wired it wrong. I am able to open up the serial monitor/plotter and see in information changing so my other component is also working so the problem must be in the code...
#include <LiquidCrystal.h>
/**
* LIDARLite I2C Example
* Author: Garmin
* Modified by: Shawn Hymel (SparkFun Electronics)
* Date: June 29, 2017
*
* Read distance from LIDAR-Lite v3 over I2C
*
* See the Operation Manual for wiring diagrams and more information:
* http://static.garmin.com/pumac/LIDAR_Lite_v3_Operation_Manual_and_Technical_Specifications.pdf
*/
#include <Wire.h>
#include <LIDARLite.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// Globals
LIDARLite lidarLite;
int cal_cnt = 0;
void setup()
{
Serial.begin(9600); // Initialize serial connection to display distance readings
lidarLite.begin(0, true); // Set configuration to default and I2C to 400 kHz
lidarLite.configure(0); // Change this number to try out alternate configurations
lcd.begin(16, 2);
// initialize the serial communications:
}
void loop()
{
int dist;
// At the beginning of every 100 readings,
// take a measurement with receiver bias correction
if ( cal_cnt == 0 ) {
dist = lidarLite.distance(); // With bias correction
} else {
dist = lidarLite.distance(false); // Without bias correction
}
// Increment reading counter
cal_cnt++;
cal_cnt = cal_cnt % 100;
// Display distance
Serial.print(dist);
Serial.println(" cm");
delay(10);
// when characters arrive over the serial port...
if (Serial.available()) {
// wait a bit for the entire message to arrive
delay(100);
// clear the screen
lcd.clear();
// read all the available characters
while (Serial.available() > 0) {
// display each character to the LCD
lcd.write(Serial.read());
}
}
}
The LCD should be displaying the changing measurements
The LCD is lit up and I can adjust the back light but I can't get anything to show up.
Just because the LCD is "lit" doesn't mean it's wired correctly. In fact, the backlighting circuit is usually totally separate from the data and control signals circuits. I would start by checking the assumption that it's wired correctly with a simple command to print a known value to the LCD:
lcd.clear();
lcd.println("TEST");
If this works, then you know the LCD is working and can look elsewhere for the problem.
If this doesn't work, I'd question your assumption that it's hooked up correctly, but if you still get nothing but "blue blocks" then it might be something as simple as your contrast is not correct. It can be tricky getting the contrast and brightness to a good combination for readability. See if your display has a small potentiometer (usually adjustable with a very small Philips-head driver) on the back and carefully adjust the contrast.
Brightness is often changeable through software commands but most LCDs default to high brightness when first booted up.
If changing contrast doesn't work, you may have a real wiring problem and then it really is off-topic for this forum. In that case you should sketch a schematic and post on Electrical Engineering stack.

How to send 4 Pot values via i2c from Arduino to Arduino? How to differentiate these values while receiving them?

I have one Arduino with 4 Pots. The other Arduino receives these 4 values via i2c and prints them on a Display. The problem is that I don't know how to send these 4 values that the Slave is able to know which value belongs to which Pot.
Slave Code:
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup()
{
Wire.begin(5);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
lcd.begin(16,2);
}
void loop()
{
}
void receiveEvent(int)
{
while(Wire.available())
{
//How to create this part? How does the Slave know which value belongs to which pot?
}
}
Master Code:
#include <Wire.h>
void setup()
{
Serial.begin(9600);
Wire.begin();
delay(2000);
}
void loop()
{
int sensor1 = analogRead(A1);
Wire.beginTransmission(5);
Wire.write(sensor1);
Serial.print(sensor1);
Wire.endTransmission();
delay(100);
int sensor2 = analogRead(A2);
Wire.beginTransmission(5);
Wire.write(sensor2);
Serial.print(sensor2);
Wire.endTransmission();
delay(500);
}
Ahh what we have here is a basic question on how to design I2C communication. Unfortunately Examples for I2C master and slave included in Arduino IDE are IMO too limited to provide clear guidance on this matter.
First of all in your examples the master and slaves roles are exchanged and should be switched. Slave should read values from analog inputs and master should request them. Why? Because it's master which should decide when to request values and properly decode the request. Slave should provide proper answer to a given request eliminating the problem of data interpretation.
I2C communication is based on requestFunction-(wait)-requestResponse sequence controlled by the master.
Plese refer to the range finder example on arduino page. In a nutshell:
First: master requests a function to measure distance:
// step 3: instruct sensor to return a particular echo reading
Wire.beginTransmission(112); // transmit to device #112
Wire.write(byte(0x02)); // sets register pointer to echo #1 register (0x02)
Wire.endTransmission(); // stop transmitting
(sometimes slaves need some time e.g. 10 - 50 ms to process requests but in the example I'm refering to master doesn't delay read)
Second: master requests response:
// step 4: request reading from sensor
Wire.requestFrom(112, 2); // request 2 bytes from slave device #112
Third: master tries to read and analyze response.
You should design reliable I2C communication in a similar way.
Here is how I do it; you can follow my pattern and get extensible slave implementation which will support one function: read analog inputs but can be easily extended by adding additional function codes and required processing implementation to the slave main loop
Initial remarks
some kind of a simple protocol is needed to control slave - e.g. it should support requesting functions. Supporting functions requests is not absolutely needed in such simmple scenario as reading four analog inputs but what I'm describing is a more general pattern you may use in other projects.
Slave should not perform any additional actions (like reading inputs) on request response as I2C communication may break (due to delays) and you will get partial responses etc. This is very important requirement which affect the slave design.
response (and also request if needed) can contain CRC as if master waits not long enough it may get empty response. If nobody else is going to use your code such countermeasures are not needed and will not be described here. Other important thing is Wire library buffer limitation which is 32 bytes and implementing CRC checksum without modifying the buffer length limits the available data length by two bytes (if crc16 is used).
slave:
#include <WSWire.h> // look on the web for an improved wire library which improves reliability by performing re-init on lockups
// >> put this into a header file you include at the beginning for better clarity
enum {
I2C_CMD_GET_ANALOGS = 1
};
enum {
I2C_MSG_ARGS_MAX = 32,
I2C_RESP_LEN_MAX = 32
};
#define I2C_ADDR 0
#define TWI_FREQ_SETTING 400000L // 400KHz for I2C
#define CPU_FREQ 16000000L // 16MHz
extern const byte supportedI2Ccmd[] = {
1
};
// << put this into a header file you include at the beginning for better clarity
int argsCnt = 0; // how many arguments were passed with given command
int requestedCmd = 0; // which command was requested (if any)
byte i2cArgs[I2C_MSG_ARGS_MAX]; // array to store args received from master
int i2cArgsLen = 0; // how many args passed by master to given command
uint8_t i2cResponse[I2C_RESP_LEN_MAX]; // array to store response
int i2cResponseLen = 0; // response length
void setup()
{
// >> starting i2c
TWBR = ((CPU_FREQ / TWI_FREQ_SETTING) - 16) / 2;
Wire.begin(I2C_ADDR); // join i2c bus
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent);
// << starting i2c
}
void loop()
{
if(requestedCmd == I2C_CMD_GET_ANALOGS){
// read inputs and save to response array; example (not tested) below
i2cResponseLen = 0;
// analog readings should be averaged and not read one-by-one to reduce noise which is not done in this example
i2cResponseLen++;
i2cResponse[i2cResponseLen -1] = analogRead(A0);
i2cResponseLen++;
i2cResponse[i2cResponseLen -1] = analogRead(A1);
i2cResponseLen++;
i2cResponse[i2cResponseLen -1] = analogRead(A2);
i2cResponseLen++;
i2cResponse[i2cResponseLen -1] = analogRead(A3);
// now slave is ready to send back four bytes each holding analog reading from a specific analog input; you can improve robustness of the protocol by including e.g. crc16 at the end or instead of returning just 4 bytes return 8 where odd bytes indicate analog input indexes and even bytes their values; change master implementation accordingly
requestedCmd = 0; // set requestd cmd to 0 disabling processing in next loop
}
else if (requestedCmd != 0){
// log the requested function is unsupported (e.g. by writing to serial port or soft serial
requestedCmd = 0; // set requestd cmd to 0 disabling processing in next loop
}
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent(){
Wire.write(i2cResponse, i2cResponseLen);
}
// function that executes when master sends data (begin-end transmission)
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
//digitalWrite(13,HIGH);
int cmdRcvd = -1;
int argIndex = -1;
argsCnt = 0;
if (Wire.available()){
cmdRcvd = Wire.read(); // receive first byte - command assumed
while(Wire.available()){ // receive rest of tramsmission from master assuming arguments to the command
if (argIndex < I2C_MSG_ARGS_MAX){
argIndex++;
i2cArgs[argIndex] = Wire.read();
}
else{
; // implement logging error: "too many arguments"
}
argsCnt = argIndex+1;
}
}
else{
// implement logging error: "empty request"
return;
}
// validating command is supported by slave
int fcnt = -1;
for (int i = 0; i < sizeof(supportedI2Ccmd); i++) {
if (supportedI2Ccmd[i] == cmdRcvd) {
fcnt = i;
}
}
if (fcnt<0){
// implement logging error: "command not supported"
return;
}
requestedCmd = cmdRcvd;
// now main loop code should pick up a command to execute and prepare required response when master waits before requesting response
}
master:
#include <WSWire.h>
#define I2C_REQ_DELAY_MS 2 // used for IO reads - from node's memory (fast)
#define I2C_REQ_LONG_DELAY_MS 5 //used for configuration etc.
#define TWI_FREQ_SETTING 400000L
#define CPU_FREQ 16000000L
enum {
I2C_CMD_GET_ANALOGS = 1
};
int i2cSlaveAddr = 0;
void setup(){
// joining i2c as a master
TWBR = ((CPU_FREQ / TWI_FREQ_SETTING) - 16) / 2;
Wire.begin();
}
void loop(){
//requesting analogs read:
Wire.beginTransmission(i2cSlaveAddr);
Wire.write((uint8_t)I2C_CMD_GET_ANALOGS);
Wire.endTransmission();
delay(I2C_REQ_DELAY_MS);
// master knows slave should return 4 bytes to the I2C_CMD_GET_ANALOGS command
int respVals[4];
Wire.requestFrom(i2cSlaveAddr, 4);
uint8_t respIoIndex = 0;
if(Wire.available())
for (byte r = 0; r < 4; r++)
if(Wire.available()){
respVals[respIoIndex] = (uint8_t)Wire.read();
respIoIndex++;
}
else{
// log or handle error: "missing read"; if you are not going to do so use r index instead of respIoIndex and delete respoIoIndex from this for loop
break;
}
// now the respVals array should contain analog values for each analog input in the same order as defined in slave (respVals[0] - A0, respVals[1] - A1 ...)
}
I hope my example will help. It's based on code working for weeks making 40 reads a second from multiple slaves however I have not compiled it to test the function you require.
Please use WSWire library as the Wire (at least as for Arduino 1.0.3) may occasionally freeze your master if for some reason slave will not respond to request.
EDIT: The WSWire lib requires external pull-up resistors for I2C unless you modify the source and enable internal pull-ups like Wire does.
EDIT: instead of creating i2c slave implementation you may try the EasyTransfer library. I haven't tried it but it may be easier to use it if sending four bytes is everything you need.
EDIT[12.2017]: There is a new player on the block - PJON - a library suited for easy multi-master communication ideal to exchange pot values (and much more). It's been around for some time but gained a substantial development speed in recent months. I'm partially involved in its development and switched all field-level and local buses I've used so far (I2C, MODBUS RTU) to PJON over single wire, hardware serial or RF.
Check out GitHub-I2CBus, I've done the exact same thing. Hope it can help

receiving data from pc to PIC 16F877A with compiler hi-tech

I try to send the data from pc to the pic microcontroller. I am a beginner in PIC.
I send the data from hyperterminal and the data will display in the led in port B of PIC.
I used 10Mhz clock and the connection in 9600 baudrate.
here my uart.h program:
char UART_Init(const long int baudrate)
{
unsigned int x;
x = (_XTAL_FREQ - baudrate*64)/(baudrate*64);
if(x>255)
{
x = (_XTAL_FREQ - baudrate*16)/(baudrate*16);
BRGH = 1;
}
if(x<256)
{
SPBRG = x;
SYNC = 0;
SPEN = 1;
TRISC7 = 1;
TRISC6 = 1;
CREN = 1;
TXEN = 1;
return 1;
}
return 0;
}
char UART_TX_Empty()
{
return TRMT;
}
char UART_Data_Ready()
{
return RCIF;
}
char UART_Read()
{
while(!RCIF);
return RCREG;
}
void UART_Read_Text(char *Output, unsigned int length)
{
int i;
for(int i=0;i<length;i++)
Output[i] = UART_Read();
}
void UART_Write(char data)
{
while(!TRMT);
TXREG = data;
}
void UART_Write_Text(char *text)
{
int i;
for(i=0;text[i]!='\0';i++)
UART_Write(text[i]);
}
and this is my main program:
#include<htc.h>
#include<pic.h>
#define _XTAL_FREQ 10000000 //Clock Frequency
#include "uart.h"
void main()
{
TRISB = 0x00; //PORTB as Output
UART_Init(9600);
do
{
if(UART_Data_Ready())
PORTB = UART_Read();
__delay_ms(1000);
}while(1);
}
in hyperteminal I send data say 10010010 but the led in port B do not respond, are there any error in my program?
You have several steps: initialize UART, initialize LEDs, communicate over UART and setup your PC's UART. Which components have you successfully written and tested? You say you're a beginner, so what is the smallest functional program you have successfully executed on a PIC? I've been working with microcontrollers for years, but I still schedule about a whole day to get a single LED to turn on because it could be a software problem, a hardware problem, a voltage problem, an oscillator problem, a PCB problem or a compiler problem.
Here are the steps I take for microchip bring up:
Go over the oscillator section, the configuration bits section, the watchdog section and the pinout section (looking for VDD and VSS) in the datasheet. These are some of the hardest parts to get right. (A gotcha about the oscillator: just because you can program a chip, doesn't mean the oscillator is working because the programmer provides it's own clock.)
Write the bare-minimum code to turn on a single LED.
Write the bare-minimum code to make the LED blink (just use a for-loop delay for now, timers come later)
Write UART initialization code and transmit a single character, I use captial U because it's pretty in binary. TXREG = 'U';
Connect the UART to a PC and see if the hyperterminal sees the U. If it doesn't, I connect an oscilscope to the lines to make sure that the PIC is transmitting, that the PC transmits when I type characters and that the timing of the edges matches.
Within the PIC code, have the UART echo characters from the terminal. (TXREG = RXREG;), and then type on the hyperterminal and make sure the characters are echoed back.
One more note:
Do not have the PIC perform the SPBRG calculation. PIC16 are 8-bit processors and 10000000 requires 32-bits to store. There might be hiccups with the integer divison. It might not have a bug in it, but there's no need to have the PIC calculate it each time. Calculate it before-hand and hard-code the value.

Resources