USART transmit problems on a PIC - c

I'm trying to send data to an SD card from a PIC18f4580, but the PIC is not sending what it should be.
related global variables:
unsigned char TXBuffer[128]; //tx buffer
unsigned char TXCurrentPos = 0x00; //tracks the next byte to be sent
unsigned char TXEndPos = 0x00; //tracks where new data should be put into the array
I am adding data to a buffer using the following function:
void addToBuffer(char data){
TXBuffer[TXEndPos] = data;
TXEndPos++;
}
And putting the data from the TXBuffer into TXREG with the following interrupt:
else if (PIR1bits.TXIF == 1){
if((TXEndPos - TXCurrentPos) > 0){ // if there is data in the buffer
TXREG = TXBuffer[TXCurrentPos]; // send next byte
TXCurrentPos++; // update to the new position
}
Using an oscilloscope I am able to see that the PIC is sending 0x98, regardless of what I put into the buffer. In fact I never put 0x98 into the buffer.
However, if I replace
TXREG = TXBuffer[TXCurrentPos];
with
TXREG = 0x55;
or
TXREG = TXCurrentPos;
then I get the expected results, that is the PIC will send 0x55 repeatedly, or count up from 0 respectively.
So why does the PIC have trouble sending data from the array, but any other time it is fine? I'll emphasize that transferring is handled in an interrupt, because I feel like that's the root of my issue.
EDIT: It is a circular buffer in the sense that TXEndPos and TXCurrentPos return to 0 when they reach 127.
I also disable the transmit interrupt when TXEndPos - TXCurrentPos == 0, and re-enable it when adding data to the buffer. Really, my code works completely as expected in that if I add 13 characters to TXBuffer in main, my PIC will transmit 13 characters and then stop. The problem is that they are always the same (wrong) character - 0x98.
EDIT2: more complete functions are here: http://pastebin.com/MyYz1Qzq

Perhaps TXBuffer doesn't really contain the data you think it does? Maybe you're not calling addToBuffer or calling it at the wrong time or with the wrong parameter?
You can try something like this in your interrupt handler:
TXBuffer[TXCurrentPos] = TXCurrentPos;
TXREG = TXBuffer[TXCurrentPos];
TXCurrentPos++;
Just to prove to yourself you can read and write to TXBuffer and send that to the USART.
Also try:
TXREG = TXEndPos;
To see if this matches your expectation (= the length of your message).
I am assuming there's some other code we're not seeing here that takes care of starting the transmission. Also assuming this is done per message with the position being reset between messages - i.e. this is not supposed to be a circular buffer.
EDIT: Based on looking at the more recently posted code:
Don't you need to kickstart the transmitter by writign the first byte of your buffer to TXREG? What I would normally do is enable the interrupt and write the first byte into the transmit register and a quick look at the datasheet seems to indicate that's what you need to do. Another thing is I still don't see how you ensure a wraparound from 127 to 0?
Also your main() seems to just end abruptly, where does the execution continue once main ends?

There are a lot of things you are not taking care of. TXBuffer needs to be a circular buffer. Once you increment TXEndPos past 127 then you need to wrap it back to 0. Same for TXCurrrentPos. That also affects the test to see if there's something in the buffer, the > 0 test isn't good enough. Generic advice is available here.

Your code is incomplete, but it looks wrong as-is: what happens if there is nothing to send? You don't seem to load TXREG then, so why would anything be transmitted, be it 0x98 or anything else?
The way it is usually done when this kind of code architecture is used is to turn off TXIE if there is nothing to send (in a else part of the IRQ routine), and turn it on unconditionally at the end of the addToBuffer function (since you then know for sure that there is at least one character to send).
Also, you should test TXEndPos and TXCurrentPos for equality directly, since that would let you use a circular buffer very easily by adding two modulo operations.

Related

AVR gcc, weird array behaviour

it's the first time I see something like this. I'm starting to suspect it's a hardware fault.
whenever I try to send the contents of array "test" and that array is larger than 4 elements or I initialize all elements in the declaration it contains 0xff instead of values I try to initialise with.
this works fine. when I read values from the array in while(sending them to the lcd and uart) both readouts are consistent with test values:
uint8_t i=0;
uint8_t test[4] = {1,2,3,4};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
this doesn't, it returns 0xff instead of test[i] value:
uint8_t i=0;
uint8_t test[5] = {1,2,3,4,5};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
but this works! it returns proper values
uint8_t i=0;
uint8_t test[6] = {1,2,3,4,5};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
this also works:
uint8_t i=0;
uint8_t test[5];
test[0]=1;
test[1]=2;
test[2]=3;
test[3]=4;
test[4]=5;
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
it works fine when compiled on linux
I swapped out an mcu for a different one and it works the way it should. must be an hardware problem
In first example you are going out of bounds of array test[4]. You are running while 5 times, when array has only 4 items length.
I think your problem is that you're overloading the USART. I assume that GLCD_WriteData() is VERY quick, and that USART_Transmit() buffers the character for transmission and then quickly returns. I don't know your hardware, so I can't tell - but a four-character buffer for a USART sounds reasonable.
Your five-character examples don't work because the actual character that you're trying to transmit is lost - so it puts an 0xFF in instead. You need to check the state of the USART buffer and wait for it to show that space is available (note NOT empty - that'd be inefficient!).
In the 8250 and 16450 UART chips there are two status bits:
TSRE says that the Transmit Shift Register is Empty;
THRE says that the Transmit Holding Register is Empty.
THRE can be set even when TSRE isn't - it's busy. I'd test TSRE and not send the next character until there's room - or set up a buffer and an interrupt handler.
If it's not the I/O hardware, then the only other thing that I can think of is the compiler is producing incorrect code. What is the exact declaration of USART_Transmit()? Does it expect a uint8_t? Or something else, like an int (for some reason)?
If it's something else, like int, please try the following code:
while(i<5){
int c = test[i]; // Whatever USART_Transmit wants
GLCD_WriteData(test[i]);
USART_Transmit(c);
i++;
} // while
If that always works, then you've got a compiler problem, not a hardware problem.
EDIT: Code for USART_Transmit() provided:
void USART_Transmit( uint8_t data ) {
//Wait for empty transmit buffer
while( !( UCSR0A & (1<<UDRE0)) );
//Put data into buffer, sends the data
UDR0 = data;
}
You've got something better than JTAG - you've got an LCD display! Although I don't know how many characters it has, or how long it takes to transmit a character...
You could try something like:
char Hex(uint8_t nibble) {
return nibble<10 ?
'0'+nibble :
'A'+nibble-10;
} // Hex
...
void Send(uint8_t c) {
uint8_t s;
UDR0 = c; // Send character NOW: don't wait!
do {
s = UCSR0A; // Get current USART state
//s = UCSR0A & (1<<UDRE0); // Or this: isolate ready bit...
GLCD_WriteData('x');
GLCD_WriteData(Hex(s >> 4)); // Write state-hi hex
GLCD_WriteData(Hex(s & 0xF)); // Write state-lo hex
} while (!(s & (1<<UDRE0))); // Until is actually ready
} // Send(c)
...
Send('A');
Send('B');
Send('C');
Assuming that UDRE0 is 3, then that code will result in a sequence like x00x00x00x00x00x08x00x00x00x00x08x00x00x00x08 if it is working. If it produces x08x08x08 then you've got a stuck UCSR0A bit, and it's hardware.
Old question, but giving my feedback since this is the first place I got sent while searching solution for same issue, getting even exact same results with the code samples in original question.
For me it was a bad Makefile that caused some sections to be left out by avr-objcopy as far as I know.
For example in my case, the original parameters for building my sample hex that were causing this issue:
${OBJCOPY} -j .text -O ihex led.elf led.hex
What worked a bit better:
${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

How to design a function which identifies when "+IPD," is arrived from UART?

I'm working with the Tiva Launchpad EK-TM4C123GXL and the ESP8266 WIFI module.
When this module gets a wifi packet, it sends it to the microcontroller through the UART port.
The format used by ESP8266 to send a packet (to the uC via UART) is:
+IPD,n:xxxxx\r\nOK\r\n
where:
n is the length (in bytes) of the data packet
: indicates that the next byte will be the first data byte
xxxxx is the data packet
\r\nOK\r\n are 6 bytes and they are useless for me.
For example:
+IPD,5:hello\r\nOK\r\n
Here is my situation:
I'm working on an existing project, where I can't change these two things:
1- The UART module is already configured to generate an interrupt when its Receive FIFO (of 16 bytes) is half-full.
2- The ISR (Interrupt Service Routine) which handles this interrupt:
reads only one byte from the UARTDR (UART Data Register)
saves it into a variable
calls a function (called rx_data()) which will handle that byte.
Now, I have to write this function, called rx_data(), in C language.
So, the message coming form the ESP8266 module is passed to this function, rx_data(), one byte at a time, and this function must be able to:
identify the header +IPD,
read the length n of the data packet
save the data packet xxxxx (which is located after the : character and before the first \r character) into a buffer
discard the final bytes \r\nOK\r\n (these 6 bytes are useless for me, but, anyway, I must read them to remove them from the Receive FIFO)
I think to work step by step, so now I' m reasoning on:
how to identify the +IPD, , considering that only one byte at a time is passed to this function?
It's time to make a state machine. Every time rx_data is called, you would update the state of your state machine, and eventually at some point you will know that you have received the string "+IPD,".
The simplest thing that could work would be something like this, assuming that the byte received from the UART is passed as an argument to rx_data:
void rx_data(uint8_t byte)
{
static uint8_t state = 0;
if (byte == '+') { state = 1; }
else if (state == 1 && byte == 'I') { state = 2; }
else if (state == 2 && byte == 'P') { state = 3; }
else if (state == 3 && byte == 'D') { state = 4; }
else if (state == 4 && byte == ',') {
state = 0;
handleIPDMessage(); // we received "+IPD,"
}
else { state = 0; }
}
You can see that handleIPDMessage() is called if and only if the last characters received were "+IPD,".
However, you should consider writing a more general state machine that would operate on lines instead of just looking for this one string. That would probably be easier to write and more robust. When a complete line is received, you would call a function named handleLineReceived() to handle that line. That function would have access to a buffer with the entire line, and it could parse it in whatever way it wants to. (Just be careful that you never write beyond the end of that buffer.)
By the way, I wouldn't be putting logic like that in an ISR. It's generally best to keep ISRs simple and fast. If you are not doing so already, store the byte to a circular buffer in the ISR and then read from the circular buffer in your main loop, and every time you read a byte from the circular buffer then call a function like the rx_data function described above to process the byte.

Reading serial port faster

I have a computer software that sends RGB color codes to Arduino using USB. It works fine when they are sent slowly but when tens of them are sent every second it freaks out. What I think happens is that the Arduino serial buffer fills out so quickly that the processor can't handle it the way I'm reading it.
#define INPUT_SIZE 11
void loop() {
if(Serial.available()) {
char input[INPUT_SIZE + 1];
byte size = Serial.readBytes(input, INPUT_SIZE);
input[size] = 0;
int channelNumber = 0;
char* channel = strtok(input, " ");
while(channel != 0) {
color[channelNumber] = atoi(channel);
channel = strtok(0, " ");
channelNumber++;
}
setColor(color);
}
}
For example the computer might send 255 0 123 where the numbers are separated by space. This works fine when the sending interval is slow enough or the buffer is always filled with only one color code, for example 255 255 255 which is 11 bytes (INPUT_SIZE). However if a color code is not 11 bytes long and a second code is sent immediately, the code still reads 11 bytes from the serial buffer and starts combining the colors and messes them up. How do I avoid this but keep it as efficient as possible?
It is not a matter of reading the serial port faster, it is a matter of not reading a fixed block of 11 characters when the input data has variable length.
You are telling it to read until 11 characters are received or the timeout occurs, but if the first group is fewer than 11 characters, and a second group follows immediately there will be no timeout, and you will partially read the second group. You seem to understand that, so I am not sure how you conclude that "reading faster" will help.
Using your existing data encoding of ASCII decimal space delimited triplets, one solution would be to read the input one character at a time until the entire triplet were read, however you could more simply use the Arduino ReadBytesUntil() function:
#define INPUT_SIZE 3
void loop()
{
if (Serial.available())
{
char rgb_str[3][INPUT_SIZE+1] = {{0},{0},{0}};
Serial.readBytesUntil( " ", rgb_str[0], INPUT_SIZE );
Serial.readBytesUntil( " ", rgb_str[1], INPUT_SIZE );
Serial.readBytesUntil( " ", rgb_str[2], INPUT_SIZE );
for( int channelNumber = 0; channelNumber < 3; channelNumber++)
{
color[channelNumber] = atoi(channel);
}
setColor(color);
}
}
Note that this solution does not require the somewhat heavyweight strtok() processing since the Stream class has done the delimiting work for you.
However there is a simpler and even more efficient solution. In your solution you are sending ASCII decimal strings then requiring the Arduino to spend CPU cycles needlessly extracting the fields and converting to integer values, when you could simply send the byte values directly - leaving if necessary the vastly more powerful PC to do any necessary processing to pack the data thus. Then the code might be simply:
void loop()
{
if( Serial.available() )
{
for( int channelNumber = 0; channelNumber < 3; channelNumber++)
{
color[channelNumber] = Serial.Read() ;
}
setColor(color);
}
}
Note that I have not tested any of above code, and the Arduino documentation is lacking in some cases with respect to descriptions of return values for example. You may need to tweak the code somewhat.
Neither of the above solve the synchronisation problem - i.e. when the colour values are streaming, how do you know which is the start of an RGB triplet? You have to rely on getting the first field value and maintaining count and sync thereafter - which is fine until perhaps the Arduino is started after data stream starts, or is reset, or the PC process is terminated and restarted asynchronously. However that was a problem too with your original implementation, so perhaps a problem to be dealt with elsewhere.
First of all, I agree with #Thomas Padron-McCarthy. Sending character string instead of a byte array(11 bytes instead of 3 bytes, and the parsing process) is wouldsimply be waste of resources. On the other hand, the approach you should follow depends on your sender:
Is it periodic or not
Is is fixed size or not
If it's periodic you can check in the time period of the messages. If not, you need to check the messages before the buffer is full.
If you think printable encoding is not suitable for you somehow; In any case i would add an checksum to the message. Let's say you have fixed size message structure:
typedef struct MyMessage
{
// unsigned char id; // id of a message maybe?
unsigned char colors[3]; // or unsigned char r,g,b; //maybe
unsigned char checksum; // more than one byte could be a more powerful checksum
};
unsigned char calcCheckSum(struct MyMessage msg)
{
//...
}
unsigned int validateCheckSum(struct MyMessage msg)
{
//...
if(valid)
return 1;
else
return 0;
}
Now, you should check every 4 byte (the size of MyMessage) in a sliding window fashion if it is valid or not:
void findMessages( )
{
struct MyMessage* msg;
byte size = Serial.readBytes(input, INPUT_SIZE);
byte msgSize = sizeof(struct MyMessage);
for(int i = 0; i+msgSize <= size; i++)
{
msg = (struct MyMessage*) input[i];
if(validateCheckSum(msg))
{// found a message
processMessage(msg);
}
else
{
//discard this byte, it's a part of a corrupted msg (you are too late to process this one maybe)
}
}
}
If It's not a fixed size, it gets complicated. But i'm guessing you don't need to hear that for this case.
EDIT (2)
I've striked out this edit upon comments.
One last thing, i would use a circular buffer. First add the received bytes into the buffer, then check the bytes in that buffer.
EDIT (3)
I gave thought on comments. I see the point of printable encoded messages. I guess my problem is working in a military company. We don't have printable encoded "fire" arguments here :) There are a lot of messages come and go all the time and decoding/encoding printable encoded messages would be waste of time. Also we use hardwares which usually has very small messages with bitfields. I accept that it could be more easy to examine/understand a printable message.
Hope it helps,
Gokhan.
If faster is really what you want....this is little far fetched.
The fastest way I can think of to meet your needs and provide synchronization is by sending a byte for each color and changing the parity bit in a defined way assuming you can read the parity and bytes value of the character with wrong parity.
You will have to deal with the changing parity and most of the characters will not be human readable, but it's gotta be one of the fastest ways to send three bytes of data.

An Audio Buffer after mpg123_read, what is it? How can I manipulate it?

This is the example code:
while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
{
// -> I'm consider this line
if((ao_play(dev, (char*)buffer, done)==0)){
}
}
In this code i want to edit the audio before it's played. Anyone suggest me to use fft to do this, personally i'm try to do this:
while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
{
buffer=((int)buffer)*2
if((ao_play(dev, (char*)buffer, done)==0))
}
for experiment, but this can't do anything. So, what is a buffer? How i can change it in real time? And can i stop it and after resume it (also called "pause" in music player..)?
Sorry for noob questions but I'm starting to program just from 6 months.
A buffer is a memory block used to contain an arbitrary, up bounded amount of data. In C, it's used as an array. If the buffer is dynamically allocated, then the variable buffer is a pointer that points to the address where the actual buffer (memory block) begins. You have to look at the declaration of variable buffer to know what is the type of the elements inside such array.
Also you have to look at the mpg123 documentation to know how to interpret the data that is returned by the mpg123_read() function.
Making an educated guess based upon the nature of the data you have decoded, I would say that buffer is probably an array of interleaved short ints that comprises data for stereo channels L and R of an uncompressed 16-bit audio signal. Channel L being at even indexed elements, and channel R being at odd indexed elements.
So, a possible editing would be like this:
for (int i=0;i<done;i+=2)
{
buffer[i] = (buffer[i+1] - buffer[i]) / 2;
}
This would substract left channel data with right channel data, cancelling any audio data that is identical on both channels. It's the basic technique for cancelling vocals in a song.
Your proposed editing has no meaning. You are changing the value of the pointer buffer by multiplying it by two. That makes the pointer to have a very different memory address, much possibly illegal, so when that pointer is used in ao_play() you will get a segmentation fault.
I guess that what you want to do with your example is to make your audio data twice louder, don't you? In that case, you are looking for this:
for (int i=0;i<done;i+=2)
{
if (buffer[i]>16383)
buffer[i] = 32767;
else if (buffer[i]<-16384)
buffer[i] = -32768;
else
buffer[i] = 2*buffer[i];
}
To stop and resume, you have to find a way for your program to check the value of something you can change with an input device (a button pressed in a window, a key pressed, etc).
For example, let's say you have a function called khbit() that returns non zero if a key is being pressed (this function is present in DOS compilers and sometimes is available as non-standard library for easing portability of older DOS programs: look at conio.h if you have it). Then you can do something like this:
int paused = 0; /* flip-flop variable to pause/resume playing */
while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
{
if (!paused)
{
if((ao_play(dev, (char*)buffer, done)==0))
break;
}
if (kbhit() && getchar()==' ')
paused = !paused;
}
This will play/pause your music using the SPACE bar.
It will not pause the music, only mute it. Reading (mpg123_read) goes on so you're just skipping a part.

Can't write to SC1DRL register on 68HC12 board--what am I missing?

I am trying to write to use the multiple serial interface on the 68HC12 but am can't get it to talk. I think I've isolated the problem to not being able to write to the SC1DRL register (SCI Data Register Low).
The following is from my SCI ISR:
else if (HWRegPtr->SCI.sc1sr1.bit.tdre) {
/* Transmit the next byte in TX_Buffer. */
if (TX_Buffer.in != TX_Buffer.out || TX_Buffer.full) {
HWRegPtr->SCI.sc1drl.byte = TX_Buffer.buffer[TX_Buffer.out];
TX_Buffer.out++;
if (TX_Buffer.out >= SCI_Buffer_Size) {
TX_Buffer.out = 0;
}
TX_Buffer.full = 0;
}
/* Disable the transmit interrupt if the buffer is empty. */
if (TX_Buffer.in == TX_Buffer.out && !TX_Buffer.full) {
Disable_SCI_TX();
}
}
TX_Buffer.buffer has the right thing at index TX_Buffer.out when its contents are being written to HWRegPtr->SCI.sc1drl.byte, but my debugger doesn't show a change, and no data is being transmitted over the serial interface.
Anybody know what I'm missing?
edit:
HWRegPtr is defined as:
extern HARDWARE_REGISTER *HWRegPtr;
HARDWARE_REGISTER is a giant struct with all the registers in it, and is volatile.
It's likely that SC1DRL is a write-only register (check the official register docs to be sure -- google isn't turning up the right PDF for me). That means you can't read it back (even with an in-target debugger) to verify your code.
How is HWRegPtr defined? Does it have volatile in the right places to ensure the compiler treats every write through that pointer as something which must happen immediately?

Resources